Java Demo, Reading and Writing with Files
Notes:
- Example of reading from and writing to a text file.
- The process of opening files needs to be put inside a "try - catch" block
in case there is a problem opening the file(s). In this example, the
try-catch block catches an "IOException". "e" is the variable name for the
IOException that may occur.
- The general format for opening a file uses three classes:
BufferedReader, FileReader (for reading from files), and FileWriter (writing to files)
- The format for opening a file for reading is:
BufferedReader infile=new BufferedReader(new FileReader(filename));
"infile" is the user supplied name for the "instance" of this class created with new
- Check out:http://java.sun.com/j2se/1.3/docs/api/index.html for more info on
these classes such as BufferedReader.
-
To read a line from the text file: use the readLine() method from the
BufferedReader class. Use this syntax: instance-name.readLine()
In this program we use: line = infile.readLine()
- infile.readLine() returns a String. "line" is a String.
- outfile.write(line) writes the string "line" to a file specified by
FileWriter().
An alternative syntax is: outfile.write(line,0,line.length()); to write
a specific portion of a string.
- outfile.newLine() generates a new line.
import java.io.*; // Import the Input and Output Stream Classes
public class JavaDemo{
public static void main(String[] args){
try{
BufferedReader infile =
new BufferedReader(new FileReader("sampleFile.txt"));
// Open for reading
System.out.println("File open for reading...");
BufferedWriter outfile =
new BufferedWriter(new FileWriter("writefile.txt"));
// Open for writing
System.out.println("File open for writing...");
String line;
while((line = infile.readLine()) != null)
{
System.out.println(line); // routes output to CRT
outfile.write(line); //writes to a file
//Or use the following syntax to write a portion of a String:
// outfile.write(line, 0, line.length()); // routes output to file
outfile.newLine(); //generate a newline in the outfile
}
System.out.println("Done copying file...");
infile.close();
outfile.close();
System.out.println("Files closed.");
}
catch(IOException e){
System.err.println(e);
return;
}}}