`
xsuo
  • 浏览: 124088 次
  • 性别: 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,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 2This example demonstrates usingScannertoreada file line by line (it does not perform awriteoperation) :

  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. }
分享到:
评论

相关推荐

    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