import java.io.FileOutputStream; import java.io.IOException; public class FileOutputExample { public static void main(String[] args) { String str = "Hello, World!"; try { FileOutputStream fos = new FileOutputStream("output.txt"); byte[] b = str.getBytes(); fos.write(b); fos.close(); System.out.println("File written successfully."); } catch (IOException e) { e.printStackTrace(); } } }
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class FileOutputExample { public static void main(String[] args) { File file = new File("output.txt"); try (FileOutputStream fos = new FileOutputStream(file)) { String str = "Hello, World!"; byte[] b = str.getBytes(); fos.write(b); System.out.println("File written successfully."); } catch (IOException e) { e.printStackTrace(); } } }In the above example, we create a file object and then use it to create a file output stream using a try-with-resources block. We write the string "Hello, World!" to the file using the write() method and then the close() method is called automatically, after the end of the try block.