Upload
hariprasanna-v
View
2.440
Download
1
Embed Size (px)
Citation preview
based on OOP with Java, by David J. Barnes
Input-Output 1
The java.io Package
Text files• Reader and Writer classes
Byte stream files• InputStream, FileInputStream, OutputStream,
FileOutputStream
Primitive-data stream files• DataInputStream, DataOutputStream
Object stream files• ObjectInputStream & ObjectOutputStream
based on OOP with Java, by David J. Barnes
Input-Output 2
The File Class
A File object represents an abstract pathname.– Represents both files and directories (folders).– Name, parent directory, size, permissions.– Constructor takes the file’s name:
•File info = new File("Letter.txt");
– No exception thrown if the file does not exist.
based on OOP with Java, by David J. Barnes
Input-Output 3
Methods of the File Class
File info = new File("Letter.txt");if(info.exists()){ System.out.println("Size of "+info.getName()+ " is "+info.length()); if(info.isDirectory()){ System.out.println("The file is a directory."); } if(info.canRead()){ System.out.println("The file is readable."); } if(info.canWrite()){ System.out.println("The file is writeable."); }}
based on OOP with Java, by David J. Barnes
Input-Output 4
FileReader and FileWriter
The two main classes for reading and writing text files.– A file is opened when its name is passed to
their constructors.– Files should be closed (via close) when
finished with.– Their read and write methods deal with char
and char[].
based on OOP with Java, by David J. Barnes
Input-Output 5
Opening and Closing a Filetry{ // Try to open the file. FileReader inputFile = new FileReader(filename); // Process the file's contents. ... // Close the file now that it is finished with. inputFile.close();}catch(FileNotFoundException e){ System.out.println("Unable to open "+filename);}catch(IOException e){ // The file could not be read or closed. System.out.println("Unable to process "+filename);}
based on OOP with Java, by David J. Barnes
Input-Output 6
Copying a Text Filestatic void copyFile(FileReader inputFile, FileWriter outputFile) throws IOException { final int bufferSize = 1024; char[] buffer = new char[bufferSize]; // Read the first chunk of characters. int numberRead = inputFile.read(buffer); while(numberRead > 0){ // Write out what was read. outputFile.write(buffer,0,numberRead); numberRead = inputFile.read(buffer); } outputFile.flush();}
based on OOP with Java, by David J. Barnes
Input-Output 7
Reading Single Charactersstatic void copyFile(FileReader inputFile,
FileWriter outputFile){ try{ // Read the first character. int nextChar = inputFile.read(); // Have we reached the end of file? while(nextChar != -1){ outputFile.write(nextChar); // Read the next character. nextChar = inputFile.read(); } outputFile.flush(); } catch(IOException e){ System.out.println("Unable to copy a file."); }}
based on OOP with Java, by David J. Barnes
Input-Output 8
Buffered Reader and Writers
try{ FileReader in = new FileReader(infile); BufferedReader reader = new BufferedReader(in); FileWriter out = new FileWriter(outfile); BufferedWriter writer = new BufferedWriter(out); ... reader.close(); writer.close();}catch(FileNotFoundException e){ System.out.println(e.getMessage());}catch(IOException e){ System.out.println(e.getMessage());}
based on OOP with Java, by David J. Barnes
Input-Output 9
Line-by-Line Copying
BufferedReader reader = new BufferedReader(...);// Read the first line.String line = reader.readLine();// null returned on EOF.while(line != null){ // Write the whole line. writer.write(line); // Add the newline character. writer.newLine(); // Read the next line. line = reader.readLine();}
based on OOP with Java, by David J. Barnes
Input-Output 10
PrintWriter
try{ FileWriter out = new FileWriter(outfile); PrintWriter writer = new PrintWriter(out);
writer.println(…);writer.format(“%d…”,…);
writer.close();}catch(IOException e){ System.out.println(e.getMessage());}
based on OOP with Java, by David J. Barnes
Input-Output 11
System.in
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
based on OOP with Java, by David J. Barnes
Input-Output 12
The StringTokenizer Class
Defined in the java.util package. Splits strings into separate String tokens.
– Delimiter characters are user settable (whitespace by default).
– Will also return delimiters if required.
Simple interface– public boolean hasMoreTokens()– public String nextToken()
based on OOP with Java, by David J. Barnes
Input-Output 13
Finding Words
String line = in.readLine();while(line != null){ StringTokenizer tokenizer = new StringTokenizer(line,",;:.\"' \t"); while(tokenizer.hasMoreTokens()){ String word = tokenizer.nextToken(); // Print the next word. System.out.println(word); } line = in.readLine();}
based on OOP with Java, by David J. Barnes
Input-Output 14
The Scanner Class
Defined in the java.util package. A scanner can be created from File, InputStream, or String.
Use useDelimiter to set the delimiting pattern.
Use next to retrieve the next token and use nextInt, etc. to retrieve a token of a certain type.
based on OOP with Java, by David J. Barnes
Input-Output 15
Finding Words
String line = in.readLine();while(line != null){ Scanner sc = new Scanner(line); sc.useDelimiter(",|;|:|\\.|\"|'| |\t"); while(sc.hasNext()){ String word = sc.next(); // Print the next word. System.out.println(word); } line = in.readLine();}
based on OOP with Java, by David J. Barnes
Input-Output 16
The Stream Classes
Several classes that deliver input as a stream of raw bytes, or write raw bytes.– BufferedInputStream, FileInputStream.– BufferedOutputStream,FileOutputStream.
Their read and write methods take byte[] rather than char[] arguments.
based on OOP with Java, by David J. Barnes
Input-Output 17
Manipulating Primitive Data Files DataInputStream
– readBoolean(),readChar(),readInt()...
DataOutputStream– writeBoolean(),writeChar(),writeInt(),....
based on OOP with Java, by David J. Barnes
Input-Output 18
Reading from URLsimport java.net.*;import java.io.*;public class URLReader { public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");BufferedReader in = new BufferedReader(
new InputStreamReader(yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) System.out.println(inputLine);
in.close();
}}
based on OOP with Java, by David J. Barnes
Input-Output 19
Review
Input-Output is usually difficult to perform in a platform-independent way.
The java.io package provides the required independence.
The File class supplies details of external files.
Use Reader and Writer classes for text files.
based on OOP with Java, by David J. Barnes
Input-Output 20
Review (cont.)
Use Buffered classes for input-output efficiency.
Use Stream classes when access to binary data is required.
Use DataInputStream and DataOutputStream when access to primitive data is required
StringTokenizer is useful for breaking up textual input.