Java write to file

There are n number of ways to achieve this.

  • Using PrintWriter
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");

writer.println("The first line");

writer.println("The second line");

writer.close();

 

  • Using Writer
Writer writer = null;
try {

   writer = new BufferedWriter(new OutputStreamWriter(

   new FileOutputStream("filename.txt"), "utf-8"));

   writer.write("Something");

} catch (IOException ex) {
}
finally {
try {writer.close();} catch (Exception ex) {/*ignore*/}
}

 

    FileOutputStream is = new FileOutputStream("C:\XYZ.txt");

    OutputStreamWriter osw = new OutputStreamWriter(is);  

    Writer w = new BufferedWriter(osw);

    w.write("POTATO!!!");

    w.close();

 

  • After java 7 introduction the same can be done using File class present in “nio” package
List<String> lines = Arrays.asList("The first line", "The second line");

Path file = Paths.get("the-file-name.txt");

Files.write(file, lines, Charset.forName("UTF-8"));

Here instead of this last line there are other utils which can also be used like

FileUtils.writeStringToFile(file, lines, "UTF-8");

 

Leave A Comment

Your email address will not be published. Required fields are marked *