Java Reference
In-Depth Information
Creating the Output Stream
To write to a file, you need to create an object of the FileOutputStream class, which will represent the output stream.
// Create a file output stream
FileOutputStream fos = new FileOutputStream(destFile);
When the data sink for an output stream is a file, Java tries to create the file if the file does not exist. Java may
throw a FileNotFoundException if the file name that you have used is a directory name, or if it could not open the file
for any reason. You must be ready to handle this exception by placing your code in a try-catch block, as shown:
try {
FileOutputStream fos = new FileOutputStream(srcFile);
}
catch (FileNotFoundException e){
// Error handling code goes here
}
If your file contains data at the time of creating a FileOutputStream , the data will be erased. If you want to keep
the existing data and append the new data to the file, you need to use another constructor of the FileOutputStream
class, which accepts a boolean flag for appending the new data to the file.
// To append data to the file, pass true in the second argument
FileOutputStream fos = new FileOutputStream(destFile, true);
Writing the Data
Write data to the file using the output stream. The FileOutputStream class has an overloaded write() method to
write data to a file. You can write one byte or multiple bytes at a time using the different versions of this method.
You need to place the code for writing data to the output stream in a try-catch block because it may throw an
IOException if data cannot be written to the file.
Typically, you write binary data using a FileOutputStream . If you want to write a string such as “ Hello ” to the
output stream, you need to convert the string to bytes. The String class has a getBytes() method that returns an
array of bytes that represents the string. You write a string to the FileOutputStream as follows:
String text = "Hello";
byte[] textBytes = text.getBytes();
fos.write(textBytes);
You want to write four lines of text to luci2.txt . You need to insert a new line after every line for the first three
lines of text. A new line is different on different platforms. You can get a new line for the platform on which your
program is running by reading the line.separator system variable as follows:
// Get the newline for the platform
String lineSeparator = System.getProperty("line.separator");
Note that a line separator may not necessarily be one character. To write a line separator to a file output stream,
you need to convert it to a byte array and write that byte array to the file as follows:
fos.write(lineSeparator.getBytes());
 
Search WWH ::




Custom Search