Writing file in java can be done in various ways. We will see some ways along with the code.
Writing File in java using FileOutputStream and BufferedOutputStream
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public static void usingBufferedOutputStream() { String CONTENT_TO_WRITE = "This is test content that we will write in a file"; File fout = new File("c:\\testFileForWriting.txt"); try (FileOutputStream fos = new FileOutputStream(fout); BufferedOutputStream bos = new BufferedOutputStream(fos)) { byte data[] = CONTENT_TO_WRITE.getBytes(); bos.write(data, 0, data.length); System.out.println("Written a file !!!!"); } catch (Exception e) { System.err.println("Error while writing file" + e.getMessage()); } } |
Please Note:
FileOutputStream has another construtor that is
FileOutputStream(File file, boolean append)
If append = true , then the contents that we need to write are appended to the existing contents of the file, else the existing contents are overwritten.
Writing File in java using BufferedWriter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public static void usingBufferedWriter() { String CONTENT_TO_WRITE = "This is test content that we will write in a file"; try (FileWriter fWriter = new FileWriter("c:\\testFileForWriting.txt"); BufferedWriter bufferedWriter = new BufferedWriter(fWriter)) { bufferedWriter.write(CONTENT_TO_WRITE); System.out.println("Written a file !!!!"); } catch (IOException e) { System.err.println("Error while writing file" + e.getMessage()); } } |
Please Note:
FileWriter has another construtor that is
FileWriter(String fileName, boolean append)
If append = true , then the contents that we need to write are appended to the existing contents of the file, else the existing contents are overwritten.