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:
-
importjava.io.*;
-
-
publicclassReadWriteTextFile{
-
-
-
-
staticpublicStringgetContents(FileaFile){
-
-
StringBuildercontents=newStringBuilder();
-
try{
-
-
-
BufferedReaderinput=newBufferedReader(newFileReader(aFile));
-
try{
-
Stringline=null;
-
-
-
while((line=input.readLine())!=null){
- contents.append(line);
-
contents.append(System.getProperty("line.separator"));
- }
- }
-
finally{
- input.close();
- }
- }
-
catch(IOExceptionex){
- ex.printStackTrace();
- }
-
returncontents.toString();
- }
-
-
-
-
staticpublicvoidsetContents(FileaFile,StringaContents)
-
throwsFileNotFoundException,IOException{
-
if(aFile==null){
-
thrownewIllegalArgumentException("Fileshouldnotbenull.");
- }
-
if(!aFile.exists()){
-
thrownewFileNotFoundException("Filedoesnotexist:"+aFile);
- }
-
if(!aFile.isFile()){
-
thrownewIllegalArgumentException("Shouldnotbeadirectory:"+aFile);
- }
-
if(!aFile.canWrite()){
-
thrownewIllegalArgumentException("Filecannotbewritten:"+aFile);
- }
-
-
-
Writeroutput=newBufferedWriter(newFileWriter(aFile));
-
try{
-
- output.write(aContents);
- }
-
finally{
- output.close();
- }
- }
-
-
-
publicstaticvoidmain(String...aArguments)throwsIOException{
-
FiletestFile=newFile("C:\\Temp\\blah.txt");
-
System.out.println("Originalfilecontents:"+getContents(testFile));
-
setContents(testFile,"Thecontentofthisfilehasbeenoverwritten...");
-
System.out.println("Newfilecontents:"+getContents(testFile));
- }
- }
-
Example 2
This example demonstrates using
Scanner
to
read a file line by line (it does not perform a
write operation) :
-
importjava.io.*;
-
importjava.util.Scanner;
-
publicfinalclassReadWithScanner{
-
publicstaticvoidmain(String...aArgs)throwsFileNotFoundException{
-
ReadWithScannerparser=newReadWithScanner("C:\\Temp\\test.txt");
- parser.processLineByLine();
-
log("Done.");
- }
-
-
-
publicReadWithScanner(StringaFileName){
-
fFile=newFile(aFileName);
- }
-
-
publicfinalvoidprocessLineByLine()throwsFileNotFoundException{
-
Scannerscanner=newScanner(fFile);
-
try{
-
-
while(scanner.hasNextLine()){
- processLine(scanner.nextLine());
- }
- }
-
finally{
-
- scanner.close();
- }
- }
-
-
-
protectedvoidprocessLine(StringaLine){
-
-
Scannerscanner=newScanner(aLine);
-
scanner.useDelimiter("=");
-
if(scanner.hasNext()){
- Stringname=scanner.next();
- Stringvalue=scanner.next();
-
log("Nameis:"+quote(name.trim())+",andValueis:"+quote(value.trim()));
- }
-
else{
-
log("Emptyorinvalidline.Unabletoprocess.");
- }
-
- scanner.close();
- }
-
-
privatefinalFilefFile;
-
privatestaticvoidlog(ObjectaObject){
- System.out.println(String.valueOf(aObject));
- }
-
privateStringquote(StringaText){
-
StringQUOTE="'";
-
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 ...