Reading and writing text files

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 :

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:

  1. importjava.io.*;
  2. publicclassReadWriteTextFile {
  3. /**
  4. * Fetch the entire contents of a text file, and return it in a String.
  5. * This style of implementation does not throw Exceptions to the caller.
  6. *
  7. * @param aFile is a file which already exists and can be read.
  8. */
  9. staticpublicString getContents(File aFile) {
  10. //...checks on aFile are elided
  11. StringBuilder contents =newStringBuilder();
  12. try{
  13. //use buffering, reading one line at a time
  14. //FileReader always assumes default encoding is OK!
  15. BufferedReader input =newBufferedReader(newFileReader(aFile));
  16. try{
  17. String line =null;//not declared within while loop
  18. /*
  19. * readLine is a bit quirky :
  20. * it returns the content of a line MINUS the newline.
  21. * it returns null only for the END of the stream.
  22. * it returns an empty String if two newlines appear in a row.
  23. */
  24. while(( line = input.readLine()) !=null){
  25. contents.append(line);
  26. contents.append(System.getProperty("line.separator"));
  27. }
  28. }
  29. finally{
  30. input.close();
  31. }
  32. }
  33. catch(IOException ex){
  34. ex.printStackTrace();
  35. }
  36. returncontents.toString();
  37. }
  38. /**
  39. * Change the contents of text file in its entirety, overwriting any
  40. * existing text.
  41. *
  42. * This style of implementation throws all exceptions to the caller.
  43. *
  44. * @param aFile is an existing file which can be written to.
  45. * @throws IllegalArgumentException if param does not comply.
  46. * @throws FileNotFoundException if the file does not exist.
  47. * @throws IOException if problem encountered during write.
  48. */
  49. staticpublicvoidsetContents(File aFile, String aContents)
  50. throwsFileNotFoundException, IOException {
  51. if(aFile ==null) {
  52. thrownewIllegalArgumentException("File should not be null.");
  53. }
  54. if(!aFile.exists()) {
  55. thrownewFileNotFoundException ("File does not exist: "+ aFile);
  56. }
  57. if(!aFile.isFile()) {
  58. thrownewIllegalArgumentException("Should not be a directory: "+ aFile);
  59. }
  60. if(!aFile.canWrite()) {
  61. thrownewIllegalArgumentException("File cannot be written: "+ aFile);
  62. }
  63. //use buffering
  64. Writer output =newBufferedWriter(newFileWriter(aFile));
  65. try{
  66. //FileWriter always assumes default encoding is OK!
  67. output.write( aContents );
  68. }
  69. finally{
  70. output.close();
  71. }
  72. }
  73. /** Simple test harness. */
  74. publicstaticvoidmain (String... aArguments)throwsIOException {
  75. File testFile =newFile("C:\\Temp\\blah.txt");
  76. System.out.println("Original file contents: "+ getContents(testFile));
  77. setContents(testFile,"The content of this file has been overwritten...");
  78. System.out.println("New file contents: "+ getContents(testFile));
  79. }
  80. }
Example 2 This example demonstrates using Scannerto reada file line by line (it does not perform a writeoperation) :

  1. importjava.io.*;
  2. importjava.util.Scanner;
  3. publicfinalclassReadWithScanner {
  4. publicstaticvoidmain(String... aArgs)throwsFileNotFoundException {
  5. ReadWithScanner parser =newReadWithScanner("C:\\Temp\\test.txt");
  6. parser.processLineByLine();
  7. log("Done.");
  8. }
  9. /**
  10. * @param aFileName full name of an existing, readable file.
  11. */
  12. publicReadWithScanner(String aFileName){
  13. fFile =newFile(aFileName);
  14. }
  15. /** Template method that calls {@link #processLine(String)}. */
  16. publicfinalvoidprocessLineByLine()throwsFileNotFoundException {
  17. Scanner scanner =newScanner(fFile);
  18. try{
  19. //first use a Scanner to get each line
  20. while( scanner.hasNextLine() ){
  21. processLine( scanner.nextLine() );
  22. }
  23. }
  24. finally{
  25. //ensure the underlying stream is always closed
  26. scanner.close();
  27. }
  28. }
  29. /**
  30. * Overridable method for processing lines in different ways.
  31. *
  32. *

    This simple default implementation expects simple name-value pairs, separated by an

  33. * '=' sign. Examples of valid input :
  34. *height = 167cm
  35. *mass = 65kg
  36. *disposition = "grumpy"
  37. *this is the name = this is the value
  38. */
  39. protectedvoidprocessLine(String aLine){
  40. //use a second Scanner to parse the content of each line
  41. Scanner scanner =newScanner(aLine);
  42. scanner.useDelimiter("=");
  43. if( scanner.hasNext() ){
  44. String name = scanner.next();
  45. String value = scanner.next();
  46. log("Name is : "+ quote(name.trim()) +", and Value is : "+ quote(value.trim()) );
  47. }
  48. else{
  49. log("Empty or invalid line. Unable to process.");
  50. }
  51. //(no need for finally here, since String is source)
  52. scanner.close();
  53. }
  54. // PRIVATE //
  55. privatefinalFile fFile;
  56. privatestaticvoidlog(Object aObject){
  57. System.out.println(String.valueOf(aObject));
  58. }
  59. privateString quote(String aText){
  60. String QUOTE ="'";
  61. returnQUOTE + aText + QUOTE;
  62. }
  63. }

你可能感兴趣的:(jdk,idea)