Example usage for java.io FileWriter close

List of usage examples for java.io FileWriter close

Introduction

In this page you can find the example usage for java.io FileWriter close.

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement();

    st.executeUpdate("create table survey (Id int, b CLOB);");

    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO survey VALUES(1,?)");

    File file = new File("c:/Java_Dev/data.txt");

    FileReader reader = new FileReader(file);
    pstmt.setCharacterStream(1, reader);

    pstmt.execute();/*from w w  w.j  a  v a 2s .  com*/

    ResultSet resultSet = pstmt.executeQuery("select b from survey ");

    File data = new File("C:\\a.txt");
    Reader dataReader = resultSet.getCharacterStream(1);
    FileWriter writer = new FileWriter(data);
    char[] buffer = new char[1];
    while (dataReader.read(buffer) > 0) {
        writer.write(buffer);
    }
    writer.close();

    reader.close();
    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    File outputFile = new File("jsoutput.txt");
    System.out.println("Script output will be written to " + outputFile.getAbsolutePath());

    FileWriter writer = new FileWriter(outputFile);
    ScriptContext defaultCtx = engine.getContext();
    defaultCtx.setWriter(writer);/*w w  w  .  j a  v a  2s  . c o  m*/
    String script = "print('Hello custom output writer')";
    engine.eval(script);
    writer.close();

}

From source file:bixo.tools.LengthenUrlsTool.java

/**
 * @param args - URL to fetch, or path to file of URLs
 *///from www. j a  va 2  s. co m
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
    try {
        String url = null;
        if (args.length == 0) {
            System.out.print("URL to lengthen: ");
            url = readInputLine();
            if (url.length() == 0) {
                System.exit(0);
            }

            if (!url.startsWith("http://")) {
                url = "http://" + url;
            }
        } else if (args.length != 1) {
            System.out.print("A single URL or filename parameter is allowed");
            System.exit(0);
        } else {
            url = args[0];
        }

        String filename;
        if (!url.startsWith("http://")) {
            // It's a path to a file of URLs
            filename = url;
        } else {
            // We have a URL that we need to write to a temp file.
            File tempFile = File.createTempFile("LengthenUrlsTool", "txt");
            filename = tempFile.getAbsolutePath();
            FileWriter fw = new FileWriter(tempFile);
            IOUtils.write(url, fw);
            fw.close();
        }

        System.setProperty("bixo.root.level", "TRACE");
        // Uncomment this to see the wire log for HttpClient
        // System.setProperty("bixo.http.level", "DEBUG");

        BaseFetcher fetcher = UrlLengthener.makeFetcher(10, ConfigUtils.BIXO_TOOL_AGENT);

        Pipe pipe = new Pipe("urls");
        pipe = new Each(pipe, new UrlLengthener(fetcher));
        pipe = new Each(pipe, new Debug());

        BixoPlatform platform = new BixoPlatform(LengthenUrlsTool.class, Platform.Local);
        BasePath filePath = platform.makePath(filename);
        TextLine textLineLocalScheme = new TextLine(new Fields("url"));
        Tap sourceTap = platform.makeTap(textLineLocalScheme, filePath, SinkMode.KEEP);
        SinkTap sinkTap = new NullSinkTap(new Fields("url"));

        FlowConnector flowConnector = platform.makeFlowConnector();
        Flow flow = flowConnector.connect(sourceTap, sinkTap, pipe);

        flow.complete();
    } catch (Exception e) {
        System.err.println("Exception running tool: " + e.getMessage());
        e.printStackTrace(System.err);
        System.exit(-1);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String multilineString = "This is line 1\nthis is line 2\nthis is last line";

    FileWriter fileWriter = new FileWriter("multiline.txt", true);

    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
    bufferedWriter.write(multilineString + "\n");
    bufferedWriter.flush();//ww  w.  j av a 2  s  . c om
    bufferedWriter.close();
    fileWriter.close();
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    FileWriter file = new FileWriter("a.html");
    BufferedWriter buffer = new BufferedWriter(file);
    PrintWriter out = new PrintWriter(buffer);
    out.println("<html>\n\t<body>");
    out.println("\t</body>\n</html>");
    out.close();//w  w w .java2 s.  c om
    buffer.close();
    file.close();
}

From source file:com.tomgibara.cluster.CreateGaussianCross.java

public static void main(String[] args) throws IOException {
    GaussianRandomGenerator gen = new GaussianRandomGenerator(new JDKRandomGenerator());
    final double[] center = new double[] { 0, 0 };
    int clusterSize = 300;
    FileWriter writer = new FileWriter("R/cross.txt");
    try {//from  w  ww  .  j  a  va 2s .  c o m
        writeCluster(gen, center, new double[] { 6, 1 }, clusterSize, writer);
        writeCluster(gen, center, new double[] { 1, 6 }, clusterSize, writer);
    } finally {
        writer.close();
    }
}

From source file:com.dianping.wed.cache.redis.util.TestDataUtil.java

public static void main(String[] args) {
    // ????/* www.jav a2s  .  com*/

    //&method=incr&parameterTypes=com.dianping.wed.cache.redis.dto.WeddingRedisKeyDTO&parameters={"category":"justtest","params":["1","2"]}
    List<String> opList = new ArrayList<String>(opAndKey.keySet());
    for (int i = 0; i < 1000; i++) {
        int index = RandomUtils.nextInt(opList.size());
        String op = opList.get(index);
        String key = opAndKey.get(op);
        StringBuilder result = new StringBuilder();
        int params = buildTestUrl(result, op, key);

        String fileName = "/Users/Bob/Desktop/data/data-" + params + ".csv";
        try {
            //kuka.txt
            //kuka.txt
            FileWriter writer = new FileWriter(fileName, true);
            writer.write(result.toString());
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    System.out.println("done");
}

From source file:jsonparser.ToJSON.java

public static void main(String args[]) throws FileNotFoundException, IOException {
    String text_file = "C:/Users/Kevin/Documents/NetBeansProjects/JsonParser/src/jsonparser/sample.txt";
    File file = new File(text_file);
    String s1, s2, s3;/*w w w.  ja  v  a 2s  .co m*/

    s1 = (String) FileUtils.readLines(file).get(0);
    String split1[] = s1.split("=");
    contact_id = split1[1];

    s2 = (String) FileUtils.readLines(file).get(1);
    String split2[] = s2.split("=");
    confidence_level = Float.valueOf(split2[1]);

    s3 = (String) FileUtils.readLines(file).get(2);
    String split3[] = s3.split("=");
    if (split3[1].equals(" Found")) {
        is_matched = true;
    } else {
        is_matched = false;
    }

    System.out.println("Read from text file:");
    System.out.println("contact_id =" + contact_id);
    System.out.println("confidence_level = " + confidence_level);
    System.out.println("is_matched = " + is_matched);

    FacialRecognition fr = new FacialRecognition();
    fr.setContactID(contact_id);
    fr.setConfidenceLevel(confidence_level);
    fr.setIsMatched(is_matched);
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    //convert java object to JSON format
    String json = gson.toJson(fr);

    //write JSON to a file
    try {
        //write converted json data to a file named "CountryGSON.json"  
        FileWriter writer = new FileWriter(
                "C:/Users/Kevin/Documents/NetBeansProjects/JsonParser/src/jsonparser/test.json", true);
        writer.write("" + json + ",\n");
        writer.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    //eventually need to change to send over back to client-side
    System.out.println();
    System.out.println("Coverting strings into JSON...");
    System.out.println(json);

}

From source file:contractEditor.contractHOST4.java

public static void main(String[] args) {

    JSONObject obj = new JSONObject();
    obj.put("name", "HOST4");
    obj.put("context", "VM-deployment");

    //obj.put("Context", new Integer);

    HashMap serviceDescription = new HashMap();
    serviceDescription.put("location", "France");
    serviceDescription.put("certificate", "true");
    serviceDescription.put("volume", "100_GB");
    serviceDescription.put("price", "3_euro");

    obj.put("serviceDescription", serviceDescription);

    HashMap gauranteeTerm = new HashMap();
    gauranteeTerm.put("availability", "more_98_percentage");
    obj.put("gauranteeTerm", gauranteeTerm);

    //Constraint1

    ArrayList creationConstraint1 = new ArrayList();
    ArrayList totalConstraint = new ArrayList();
    totalConstraint.add(creationConstraint1);

    obj.put("creationConstraint", totalConstraint);

    try {/*from  w w w.j  ava 2 s.  co m*/

        FileWriter file = new FileWriter("confSP" + File.separator + "Host4.json");
        file.write(obj.toJSONString());
        file.flush();
        file.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.print(obj);

    /*
            
    JSONParser parser = new JSONParser();
            
    try {
            
    Object obj2 = parser.parse(new FileReader("confSP\\confHost1.json"));
            
    JSONObject jsonObject = (JSONObject) obj2;
            
        HashMap serviceDescription2=(HashMap) jsonObject.get("serviceDescription");
                 
        method.printHashMap(serviceDescription2);
                
                
        HashMap gauranteeTerm2=(HashMap) jsonObject.get("gauranteeTerm");
                 
        method.printHashMap(gauranteeTerm2);
                
                
                
        ArrayList creationConstraint=(ArrayList) jsonObject.get("creationConstraint");
                
        method.printArrayList(creationConstraint);
            
            
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (ParseException e) {
    e.printStackTrace();
    }
            
            
            
            
            
    */

}

From source file:json.WriteToFile.java

public static void main(String[] args) {
    JSONObject countryObj = new JSONObject();
    countryObj.put("Name", "Kenya");
    countryObj.put("Population", new Integer(430000000));
    JSONArray listOfCounties = new JSONArray();
    listOfCounties.add("Nairobi");
    listOfCounties.add("Kiambu");
    listOfCounties.add("Murang'a");

    countryObj.put("Counties", listOfCounties);
    try {//from  w  ww .j a v a2 s  .c  om
        //writing to file
        File file = new File("/home/mars/Desktop/JsonExample1.json");
        file.createNewFile();
        FileWriter fw = new FileWriter(file);
        System.out.println("Writing JSON object to file");
        System.out.println("---------------------------");
        System.out.println(countryObj);

        fw.write(countryObj + "");
        fw.flush();
        fw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}