Java FileOutputStream: Write to File Guide
In Java, you can use the FileOutputStream class to output an outputstream to a file. Below is a simple example code:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class WriteToFileExample {
public static void main(String[] args) {
String filename = "output.txt";
String content = "Hello, World!";
try (OutputStream os = new FileOutputStream(filename)) {
os.write(content.getBytes());
System.out.println("Content written to file: " + filename);
} catch (IOException e) {
System.err.println("Failed to write content to file: " + filename);
e.printStackTrace();
}
}
}
In this example, we begin by specifying the file name and content to be written. Then we create an OutputStream object using the FileOutputStream class and use the write() method to write the content to the file. Finally, we catch any potential IOException that may occur and handle the exception.