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:
-
importjava.io.*;
-
-
publicclassReadWriteTextFile {
-
-
staticpublicString getContents(File aFile) {
-
StringBuilder contents =newStringBuilder();
-
-
try{
-
BufferedReader input =newBufferedReader(newFileReader(aFile));
-
try{
-
String line =null;
-
while(( line = input.readLine()) !=null){
- contents.append(line);
-
contents.append(System.getProperty("line.separator"));
- }
- }
-
finally{
- input.close();
- }
- }
-
catch(IOException ex){
- ex.printStackTrace();
- }
-
-
returncontents.toString();
- }
-
-
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);
- }
-
-
Writer output =newBufferedWriter(newFileWriter(aFile));
-
try{
- output.write( aContents );
- }
-
finally{
- output.close();
- }
- }
-
-
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));
- }
- }
-
Example 2This example demonstrates usingScannertoreada file line by line (it does not perform awriteoperation) :
-
importjava.io.*;
-
importjava.util.Scanner;
-
-
publicfinalclassReadWithScanner {
-
-
publicstaticvoidmain(String... aArgs)throwsFileNotFoundException {
-
ReadWithScanner parser =newReadWithScanner("C:\\Temp\\test.txt");
- parser.processLineByLine();
-
log("Done.");
- }
-
-
publicReadWithScanner(String aFileName){
-
fFile =newFile(aFileName);
- }
-
-
publicfinalvoidprocessLineByLine()throwsFileNotFoundException {
-
Scanner scanner =newScanner(fFile);
-
try{
-
while( scanner.hasNextLine() ){
- processLine( scanner.nextLine() );
- }
- }
-
finally{
- scanner.close();
- }
- }
-
-
protectedvoidprocessLine(String aLine){
-
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.");
- }
- scanner.close();
- }
-
-
privatefinalFile fFile;
-
-
privatestaticvoidlog(Object aObject){
- System.out.println(String.valueOf(aObject));
- }
-
-
privateString quote(String aText){
-
String QUOTE ="'";
-
returnQUOTE + aText + QUOTE;
- }
- }
分享到:
相关推荐
Downloading Graphics and Sound Files ...................................................................................... 4 Line Numbers and Spaces .....................................................
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 ...
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 ...
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 ...
• 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, ...
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-...
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 ...
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 ...
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 ...
- **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...
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 ...
- 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 ...
**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...
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 ...