try { //Creating a file output stream object FileOutputStream fos = new FileOutputStream("example.txt"); //Writing a string to the file String text = "Hello, World!"; byte[] bytes = text.getBytes(); fos.write(bytes); //Closing the file stream fos.close(); } catch (IOException e) { e.printStackTrace(); }
try { //Creating a file output stream object with append mode FileOutputStream fos = new FileOutputStream("example.txt", true); //Appending a string to the file String text = "This is a new line."; byte[] bytes = text.getBytes(); fos.write(bytes); //Closing the file stream fos.close(); } catch (IOException e) { e.printStackTrace(); }In this example, we use the same FileOutputStream object as before but with the additional constructor parameter of "true" to open the file in append mode. This allows us to add a new line of text to the existing "example.txt" file. Package Library: java.io