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, IOException and FileNotFoundException)
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 : The FileReader and FileWriter classes always 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 :

FileInputStream fis = new FileInputStream("test.txt");
InputStreamReader in = new InputStreamReader(fis, "UTF-8");

FileOutputStream fos = new FileOutputStream("test.txt");
OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");

Scanner scanner = 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. *Fetchtheentirecontentsofatextfile,andreturnitinaString.
  5. *ThisstyleofimplementationdoesnotthrowExceptionstothecaller.
  6. *
  7. *@paramaFileisafilewhichalreadyexistsandcanberead.
  8. */
  9. staticpublicStringgetContents(FileaFile){
  10. //...checksonaFileareelided
  11. StringBuildercontents=newStringBuilder();
  12. try{
  13. //usebuffering,readingonelineatatime
  14. //FileReaderalwaysassumesdefaultencodingisOK!
  15. BufferedReaderinput=newBufferedReader(newFileReader(aFile));
  16. try{
  17. Stringline=null;//notdeclaredwithinwhileloop
  18. /*
  19. *readLineisabitquirky:
  20. *itreturnsthecontentofalineMINUSthenewline.
  21. *itreturnsnullonlyfortheENDofthestream.
  22. *itreturnsanemptyStringiftwonewlinesappearinarow.
  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(IOExceptionex){
  34. ex.printStackTrace();
  35. }
  36. returncontents.toString();
  37. }

  38. /**
  39. *Changethecontentsoftextfileinitsentirety,overwritingany
  40. *existingtext.
  41. *
  42. *Thisstyleofimplementationthrowsallexceptionstothecaller.
  43. *
  44. *@paramaFileisanexistingfilewhichcanbewrittento.
  45. *@throwsIllegalArgumentExceptionifparamdoesnotcomply.
  46. *@throwsFileNotFoundExceptionifthefiledoesnotexist.
  47. *@throwsIOExceptionifproblemencounteredduringwrite.
  48. */
  49. staticpublicvoidsetContents(FileaFile,StringaContents)
  50. throwsFileNotFoundException,IOException{
  51. if(aFile==null){
  52. thrownewIllegalArgumentException("Fileshouldnotbenull.");
  53. }
  54. if(!aFile.exists()){
  55. thrownewFileNotFoundException("Filedoesnotexist:"+aFile);
  56. }
  57. if(!aFile.isFile()){
  58. thrownewIllegalArgumentException("Shouldnotbeadirectory:"+aFile);
  59. }
  60. if(!aFile.canWrite()){
  61. thrownewIllegalArgumentException("Filecannotbewritten:"+aFile);
  62. }

  63. //usebuffering
  64. Writeroutput=newBufferedWriter(newFileWriter(aFile));
  65. try{
  66. //FileWriteralwaysassumesdefaultencodingisOK!
  67. output.write(aContents);
  68. }
  69. finally{
  70. output.close();
  71. }
  72. }

  73. /**Simpletestharness.*/
  74. publicstaticvoidmain(String...aArguments)throwsIOException{
  75. FiletestFile=newFile("C:\\Temp\\blah.txt");
  76. System.out.println("Originalfilecontents:"+getContents(testFile));
  77. setContents(testFile,"Thecontentofthisfilehasbeenoverwritten...");
  78. System.out.println("Newfilecontents:"+getContents(testFile));
  79. }
  80. }

Example 2 This example demonstrates using Scanner to read a file line by line (it does not perform a write operation) :
  1. importjava.io.*;
  2. importjava.util.Scanner;
  3. publicfinalclassReadWithScanner{
  4. publicstaticvoidmain(String...aArgs)throwsFileNotFoundException{
  5. ReadWithScannerparser=newReadWithScanner("C:\\Temp\\test.txt");
  6. parser.processLineByLine();
  7. log("Done.");
  8. }
  9. /**
  10. *@paramaFileNamefullnameofanexisting,readablefile.
  11. */
  12. publicReadWithScanner(StringaFileName){
  13. fFile=newFile(aFileName);
  14. }
  15. /**Templatemethodthatcalls{@link#processLine(String)}.*/
  16. publicfinalvoidprocessLineByLine()throwsFileNotFoundException{
  17. Scannerscanner=newScanner(fFile);
  18. try{
  19. //firstuseaScannertogeteachline
  20. while(scanner.hasNextLine()){
  21. processLine(scanner.nextLine());
  22. }
  23. }
  24. finally{
  25. //ensuretheunderlyingstreamisalwaysclosed
  26. scanner.close();
  27. }
  28. }
  29. /**
  30. *Overridablemethodforprocessinglinesindifferentways.
  31. *
  32. *<P>Thissimpledefaultimplementationexpectssimplename-valuepairs,separatedbyan
  33. *'='sign.Examplesofvalidinput:
  34. *<tt>height=167cm</tt>
  35. *<tt>mass=65kg</tt>
  36. *<tt>disposition="grumpy"</tt>
  37. *<tt>thisisthename=thisisthevalue</tt>
  38. */
  39. protectedvoidprocessLine(StringaLine){
  40. //useasecondScannertoparsethecontentofeachline
  41. Scannerscanner=newScanner(aLine);
  42. scanner.useDelimiter("=");
  43. if(scanner.hasNext()){
  44. Stringname=scanner.next();
  45. Stringvalue=scanner.next();
  46. log("Nameis:"+quote(name.trim())+",andValueis:"+quote(value.trim()));
  47. }
  48. else{
  49. log("Emptyorinvalidline.Unabletoprocess.");
  50. }
  51. //(noneedforfinallyhere,sinceStringissource)
  52. scanner.close();
  53. }
  54. //PRIVATE//
  55. privatefinalFilefFile;
  56. privatestaticvoidlog(ObjectaObject){
  57. System.out.println(String.valueOf(aObject));
  58. }
  59. privateStringquote(StringaText){
  60. StringQUOTE="'";
  61. returnQUOTE+aText+QUOTE;
  62. }
  63. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值