Monday, July 20, 2009

Java Tutorial Source Code Writing to a File

Java Tutorial Source Code Writing to a File

For writing to a file, you can use the FileOutputStream class. Here is one of the constructors you can use.

FileOutputStream(String filename)

The constructor links an output stream to an actual file to write to. A FileNotFoundException is thrown when the file cannot be opened for writing.

Once the output stream is created, you can now use the stream to write to the linked file using the write method. The method has the following signature:
void write(int b)

The parameter b refers to the data to be written to the actual file associated to the output stream.

The following program demonstrates writing to a file.

import java.io.*;

class WriteFile {
public static void main(String args[]) throws IOException {
System.out.println("What is the name of the file to be
written to?");
String filename;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
filename = br.readLine();
System.out.println("Enter data to write to " + filename +
"...");
System.out.println("Type q$ to end.");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filename);
} catch (FileNotFoundException ex) {
System.out.println("File cannot be opened for
writing.");
}
try {
boolean done = false;
int data;
do {
data = br.read();
if ((char)data == 'q') {
data = br.read();
if ((char)data == '$') {
done = true;
} else {
fos.write('q');
fos.write(data);
}
} else {
fos.write(data);
}
} while (!done);
} catch (IOException ex) {
System.out.println("Problem in reading from the
file.");
}
}
}

Here is a sample run of WriteFile:

What is the name of the file to be written to?
temp.txt
Enter data to write to temp.txt...
Type q$ to end.
what a wonderful world
1, 2, step
q$

When you open temp.txt, it should contain the following:

what a wonderful world
1, 2, step

Java Tutorial Source Code Writing to a File
Java Tutorial Source Code Writing to a File
Java Tutorial Source Code Writing to a File
Java Tutorial Source Code Writing to a File
Java Tutorial Source Code Writing to a File