Sunday, January 8, 2017

Java How to write to File

In this post, I 'll show you how to write to File via  following APIs:




1. BufferedWriter.

public class WriteToFileExample {

 private static final String FILENAME = "D:\\test\\sample.txt";

 public static void main(String[] args) {

  try (BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME))) {

   String content = "Hello World\n";

   bw.write(content);
   
   System.out.println("Done");

  } catch (IOException e) {

   e.printStackTrace();

  }

 }

}

2. FileWriter


private static void writeUsingFileWriter(String data) {
        File file = new File("D:\\test\\sample.txt");        FileWriter fr = null;
        try {
            fr = new FileWriter(file);
            fr.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //close resources
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

3. Files (From JDK 7)


private static void writeUsingFiles(String data) {
        try {
            Files.write(Paths.get("D:\\test\\sample.txt"), data.getBytes());        } catch (IOException e) {
            e.printStackTrace();
        }
    }

4. Streams


private static void writeUsingOutputStream(String data) {
        OutputStream os = null;
        try {
            os = new FileOutputStream(new File("D:\\test\\sample.txt"));            os.write(data.getBytes(), 0, data.length());
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

Result: 
A file is created with content : Hello World in D:\\test\\sample.txt
Share:

0 comments:

Post a Comment

Total Pageviews