`
xsuo
  • 浏览: 123340 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

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. }

分享到:
评论

相关推荐

    Making Games with Python & PyGame.pdf(with code)

    Downloading Graphics and Sound Files ...................................................................................... 4 Line Numbers and Spaces .....................................................

    C# 7 and .NET Core: Modern Cross-Platform Development - Second Edition

    managing the filesystem, reading and writing to files and streams, text encoding, and serialization. Chapter 11, Protecting Your Data, is about protecting your data from being viewed by malicious ...

    Intergraph Standard File Formats (Element Structure)

    DGNLib is a small C/C++ library for reading and writing DGN files. Where can I get the source code? dgnlib-1.11.zip: Current standalone source with dgndump example mainline. Does DGNLib support all ...

    一个用于创建Excel XLSX文件的C库

    Libxlsxwriter is a C library that can be used to write text, numbers, formulas and hyperlinks to multiple worksheets in an Excel 2007+ XLSX file. It supports features such as: 100% compatible Excel ...

    Progamming Rust

    • Media codecs (software for reading and writing audio, video, and image files) • Media processing (for example, speech recognition or photo editing software) • Memory management (for example, ...

    TX SDK 3.08.1.0

    Java® programming access to classes and methods that are needed for reading, writing, editing and rendering .dwg files. For more details, see the section Working with Teigha for Java. Multi-...

    Automate.the.Boring.Stuff.with.Python.Practical.Programming

    Reading and Writing Files Chapter 9. Organizing Files Chapter 10. Debugging Chapter 11. Web Scraping Chapter 12. Working with Excel Spreadsheets Chapter 13. Working with PDF and word Documents ...

    Professional C# 3rd Edition

    Reading and Writing Streamed XML 786 Using the XmlTextReader Class 787 Using the XmlValidatingReader Class 791 Using the XmlTextWriter Class 794 Using the DOM in .NET 795 Using the XmlDocument Class ...

    Managing Gigabytes: Compressing and Indexing Documents and Images

    Whatever your field, if you work with large quantities of information, this book is essential reading--an authoritative theoretical resource and a practical guide to meeting the toughest storage and ...

    Algorithms and Data Structures - Niklaus Wirth

    - **Textual Input and Output**: Reading and writing text data. **Searching**: Searching algorithms are essential for finding data within a dataset. Wirth covers several techniques: - **Linear Search...

    go系统编程(英文版)

    using Go HTML template files. Lastly, it talks about reading and writing JSON data before presenting a utility that reads a number of web pages and returns the number of times a given keyword was ...

    HxD HeX Editor 英文绿色版

    - Disk-Editor: RAW reading and writing of disks and drives (WinNT and Win9x) - RAM-Editor: can read and write virtual memory of other processes - Data-folding for better overview in RAM-Editor - ...

    强大的免费的十六进制编辑器

    - You can abort nearly all operations (reading/writing files, search, replace, print...) - Display of both text (ASCII/ANSI) and hexadecimal representation - Two synchronous cursors in text and hex ...

    Problem Solving with C++ (7th edition)

    **Programming Project 17.10**: This project likely involves reading from and writing to files. #### Chapter 18: Advanced Topics This final chapter covers miscellaneous advanced topics: - **Advanced...

    Java2核心技术卷I+卷2:基础知识(第8版) 代码

    Reading and Writing Binary Data 23 ZIP Archives 32 Object Streams and Serialization 39 File Management 59 New I/O 65 Regular Expressions 75 Chapter 2: XML 87 Introducing XML 88 Parsing an ...

Global site tag (gtag.js) - Google Analytics