When reading and writing text files :
Example 2
This example demonstrates using
Scanner to
read a file line by line (it does not perform a
write operation) :
- 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)
- 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
- BufferedReader - readLine
- BufferedWriter - write + newLine
- Scanner - allows reading files in a compact way (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{
-
- /**
- *Fetchtheentirecontentsofatextfile,andreturnitinaString.
- *ThisstyleofimplementationdoesnotthrowExceptionstothecaller.
- *
- *@paramaFileisafilewhichalreadyexistsandcanberead.
- */
- staticpublicStringgetContents(FileaFile){
- //...checksonaFileareelided
- StringBuildercontents=newStringBuilder();
- try{
- //usebuffering,readingonelineatatime
- //FileReaderalwaysassumesdefaultencodingisOK!
- BufferedReaderinput=newBufferedReader(newFileReader(aFile));
- try{
- Stringline=null;//notdeclaredwithinwhileloop
- /*
- *readLineisabitquirky:
- *itreturnsthecontentofalineMINUSthenewline.
- *itreturnsnullonlyfortheENDofthestream.
- *itreturnsanemptyStringiftwonewlinesappearinarow.
- */
- while((line=input.readLine())!=null){
- contents.append(line);
- contents.append(System.getProperty("line.separator"));
- }
- }
- finally{
- input.close();
- }
- }
- catch(IOExceptionex){
- ex.printStackTrace();
- }
- returncontents.toString();
- }
-
- /**
- *Changethecontentsoftextfileinitsentirety,overwritingany
- *existingtext.
- *
- *Thisstyleofimplementationthrowsallexceptionstothecaller.
- *
- *@paramaFileisanexistingfilewhichcanbewrittento.
- *@throwsIllegalArgumentExceptionifparamdoesnotcomply.
- *@throwsFileNotFoundExceptionifthefiledoesnotexist.
- *@throwsIOExceptionifproblemencounteredduringwrite.
- */
- 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);
- }
-
- //usebuffering
- Writeroutput=newBufferedWriter(newFileWriter(aFile));
- try{
- //FileWriteralwaysassumesdefaultencodingisOK!
- output.write(aContents);
- }
- finally{
- output.close();
- }
- }
-
- /**Simpletestharness.*/
- 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));
- }
- }
-
- importjava.io.*;
- importjava.util.Scanner;
- publicfinalclassReadWithScanner{
- publicstaticvoidmain(String...aArgs)throwsFileNotFoundException{
- ReadWithScannerparser=newReadWithScanner("C:\\Temp\\test.txt");
- parser.processLineByLine();
- log("Done.");
- }
- /**
- *@paramaFileNamefullnameofanexisting,readablefile.
- */
- publicReadWithScanner(StringaFileName){
- fFile=newFile(aFileName);
- }
- /**Templatemethodthatcalls{@link#processLine(String)}.*/
- publicfinalvoidprocessLineByLine()throwsFileNotFoundException{
- Scannerscanner=newScanner(fFile);
- try{
- //firstuseaScannertogeteachline
- while(scanner.hasNextLine()){
- processLine(scanner.nextLine());
- }
- }
- finally{
- //ensuretheunderlyingstreamisalwaysclosed
- scanner.close();
- }
- }
- /**
- *Overridablemethodforprocessinglinesindifferentways.
- *
- *<P>Thissimpledefaultimplementationexpectssimplename-valuepairs,separatedbyan
- *'='sign.Examplesofvalidinput:
- *<tt>height=167cm</tt>
- *<tt>mass=65kg</tt>
- *<tt>disposition="grumpy"</tt>
- *<tt>thisisthename=thisisthevalue</tt>
- */
- protectedvoidprocessLine(StringaLine){
- //useasecondScannertoparsethecontentofeachline
- 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.");
- }
- //(noneedforfinallyhere,sinceStringissource)
- scanner.close();
- }
- //PRIVATE//
- privatefinalFilefFile;
- privatestaticvoidlog(ObjectaObject){
- System.out.println(String.valueOf(aObject));
- }
- privateStringquote(StringaText){
- StringQUOTE="'";
- returnQUOTE+aText+QUOTE;
- }
- }