Java can read several types of information from files: binary, Java objects, text, zipped files, etc. One of the most common problems is reading lines of text.
This example reads text files using the classes FileReader, BufferedReader, FileWriter, and BufferedWriter. It's a main program without a graphical user interface, taking parameters from the command line.
To change this to a graphical user interface,
you can use JFileChooser
to get a File object instead
of new File(args[...])
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
// File: io/readwrite/CopyTextFile.java // Description: Example to show text file reading and writing. // Author: Fred Swartz // Date: Februar 2005 import java.io.*; public class CopyTextFile { public static void main(String args[]) { //... Get two file names from parameters on command line. if (args.length != 2) { System.err.println("Usage: java CopyTextFile sourcefile targetfile"); System.exit(1); } //... Create File objects. File inFile = new File(args[0]); // read from first file specified File outFile = new File(args[1]); // write into second file //... Enclose in try..catch because of possible io exceptions. try { //... Create reader and writer for text files. BufferedReader reader = new BufferedReader(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); //... Loop as long as there are input lines. String line = null; while ((line=reader.readLine()) != null) { writer.write(line); writer.newLine(); // Write system dependent end of line. } //... Close reader and writer. reader.close(); // Close to unlock. writer.close(); // Close to unlock and flush to disk. } catch (IOException e) { System.err.println(e); System.exit(1); } } } |
javax.swing.JFileChooser
creates a standard file dialog and allows you to easily
get a File object for reading or writing.
See JFileChooser.
The above program does nothing with the lines of text except write them. Typically, you need to get values from the lines. There are several useful ways to extract data from the lines.
split()
method.