When reading and writing text files :
- it is almost always a good idea to use buffering (default size is 8K)
- it is often possible to use references to abstract base classes, instead of references to specific concrete classes
- there is always a need to pay attention to exceptions (in particular,IOExceptionandFileNotFoundException)
The close method :
- always needs to be called, or else resources will leak
- will automatically flush the stream, if necessary
- calling close on a "wrapper" stream will automatically call close on its underlying stream
- closing a stream a second time has no consequence
Commonly used items :
- BufferedReader- readLine
- BufferedWriter- write + newLine
- Scanner- allows reading files in a compact way (example)
TheFileReaderandFileWriterclassesalways use the system's default character encoding. If this default is not appropriate (for example, when reading an XML file which specifies its own encoding), the recommended alternatives are, for example :
FileInputStreamfis = new FileInputStream("test.txt");
InputStreamReaderin = new InputStreamReader(fis, "UTF-8");
FileOutputStreamfos = new FileOutputStream("test.txt");
OutputStreamWriterout = new OutputStreamWriter(fos, "UTF-8");
Scannerscanner = new Scanner(file, "UTF-8");
Example 1
This example uses JDK 1.5. To make it compatible with JDK 1.4, just change StringBuilder to StringBuffer:
- importjava.io.*;
- publicclassReadWriteTextFile {
- /**
- * Fetch the entire contents of a text file, and return it in a String.
- * This style of implementation does not throw Exceptions to the caller.
- *
- * @param aFile is a file which already exists and can be read.
- */
- staticpublicString getContents(File aFile) {
- //...checks on aFile are elided
- StringBuilder contents =newStringBuilder();
- try{
- //use buffering, reading one line at a time
- //FileReader always assumes default encoding is OK!
- BufferedReader input =newBufferedReader(newFileReader(aFile));
- try{
- String line =null;//not declared within while loop
- /*
- * readLine is a bit quirky :
- * it returns the content of a line MINUS the newline.
- * it returns null only for the END of the stream.
- * it returns an empty String if two newlines appear in a row.
- */
- while(( line = input.readLine()) !=null){
- contents.append(line);
- contents.append(System.getProperty("line.separator"));
- }
- }
- finally{
- input.close();
- }
- }
- catch(IOException ex){
- ex.printStackTrace();
- }
- returncontents.toString();
- }
- /**
- * Change the contents of text file in its entirety, overwriting any
- * existing text.
- *
- * This style of implementation throws all exceptions to the caller.
- *
- * @param aFile is an existing file which can be written to.
- * @throws IllegalArgumentException if param does not comply.
- * @throws FileNotFoundException if the file does not exist.
- * @throws IOException if problem encountered during write.
- */
- staticpublicvoidsetContents(File aFile, String aContents)
- throwsFileNotFoundException, IOException {
- if(aFile ==null) {
- thrownewIllegalArgumentException("File should not be null.");
- }
- if(!aFile.exists()) {
- thrownewFileNotFoundException ("File does not exist: "+ aFile);
- }
- if(!aFile.isFile()) {
- thrownewIllegalArgumentException("Should not be a directory: "+ aFile);
- }
- if(!aFile.canWrite()) {
- thrownewIllegalArgumentException("File cannot be written: "+ aFile);
- }
- //use buffering
- Writer output =newBufferedWriter(newFileWriter(aFile));
- try{
- //FileWriter always assumes default encoding is OK!
- output.write( aContents );
- }
- finally{
- output.close();
- }
- }
- /** Simple test harness. */
- publicstaticvoidmain (String... aArguments)throwsIOException {
- File testFile =newFile("C:\\Temp\\blah.txt");
- System.out.println("Original file contents: "+ getContents(testFile));
- setContents(testFile,"The content of this file has been overwritten...");
- System.out.println("New file contents: "+ getContents(testFile));
- }
- }
- importjava.io.*;
- importjava.util.Scanner;
- publicfinalclassReadWithScanner {
- publicstaticvoidmain(String... aArgs)throwsFileNotFoundException {
- ReadWithScanner parser =newReadWithScanner("C:\\Temp\\test.txt");
- parser.processLineByLine();
- log("Done.");
- }
- /**
- * @param aFileName full name of an existing, readable file.
- */
- publicReadWithScanner(String aFileName){
- fFile =newFile(aFileName);
- }
- /** Template method that calls {@link #processLine(String)}. */
- publicfinalvoidprocessLineByLine()throwsFileNotFoundException {
- Scanner scanner =newScanner(fFile);
- try{
- //first use a Scanner to get each line
- while( scanner.hasNextLine() ){
- processLine( scanner.nextLine() );
- }
- }
- finally{
- //ensure the underlying stream is always closed
- scanner.close();
- }
- }
- /**
- * Overridable method for processing lines in different ways.
- *
- *
This simple default implementation expects simple name-value pairs, separated by an
- * '=' sign. Examples of valid input :
- *height = 167cm
- *mass = 65kg
- *disposition = "grumpy"
- *this is the name = this is the value
- */
- protectedvoidprocessLine(String aLine){
- //use a second Scanner to parse the content of each line
- Scanner scanner =newScanner(aLine);
- scanner.useDelimiter("=");
- if( scanner.hasNext() ){
- String name = scanner.next();
- String value = scanner.next();
- log("Name is : "+ quote(name.trim()) +", and Value is : "+ quote(value.trim()) );
- }
- else{
- log("Empty or invalid line. Unable to process.");
- }
- //(no need for finally here, since String is source)
- scanner.close();
- }
- // PRIVATE //
- privatefinalFile fFile;
- privatestaticvoidlog(Object aObject){
- System.out.println(String.valueOf(aObject));
- }
- privateString quote(String aText){
- String QUOTE ="'";
- returnQUOTE + aText + QUOTE;
- }
- }