Beruflich Dokumente
Kultur Dokumente
Java I/O
2
Java does provide strong, flexible support for I/O as it relates to files and networks. Javas I/O system is cohesive and consistent. Java programs perform I/O through streams. A stream is an abstraction that either produces or consumes information. Input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. Output stream may refer to the console, a disk file, or a network connection. Java implements streams within class hierarchies defined in the java.io package.
Types of Streams
3
Byte Streams
4
Byte streams provide a convenient means for handling input and output of bytes. Byte streams are defined by using two class hierarchies. At the top are two abstract classes: InputStream and OutputStream. The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement. Two of the most important are read( ) and write( ).
Character Streams
6
Character streams provide a convenient means for handling input and output of characters. Character streams are defined by using two class hierarchies. At the top are two abstract classes, Reader and Writer. The abstract classes Reader and Writer define several key methods that the other stream classes implement. Two of the most important methods are read( ) and write( ).
System Class Stream Variables in, out, err System.out refers to the standard output stream. System.in refers to standard input stream. System.err refers to the standard error stream. System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream.
InputStream defines only one input method, read( ), which reads bytes.
// Read an array of bytes from the keyboard. import java.io.*; class ReadBytes { public static void main(String args[])throws IOException{ byte data[] = new byte[10]; System.out.println("Enter some characters."); System.in.read(data); System.out.print("You entered: "); for(int i=0; i < data.length; i++) System.out.print((char) data[i]); } }
PrintStream is an output stream derived from OutputStream, it also implements the lowlevel method write( ).
public static void main(String args[]) { int b; b = 'X';
System.out.write(b);
System.out.write('\n'); } }
The best class for reading console input is BufferedReader, which supports a buffered input stream. Use InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object, use the constructor shown here:
InputStreamReader(InputStream inputStream)
Since System.in refers to an object of type InputStream, it can be used for inputStream. To construct a BufferedReader use the constructor shown here:
Reading Characters
12
/* Use a BufferedReader to read characters from the console. */ import java.io.*; class ReadChars { public static void main(String ar[])throws IOException{ char c; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter characters,.'to quit."); // read characters do { c = (char) br.read(); System.out.println(c); } while(c != .'); }
Reading Strings
13
To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class.
import java.io.*; class ReadStr { public static void main(String ar[])throws IOException{ // create a BufferedReader using System.in
14
for(int i=0; i<100; i++) { str[i] = br.readLine(); if(str[i].equals("stop")) break; } System.out.println("\nHere is your file:");
PrintWriter is one of the character-based classes for console output which makes easier to internationalize your program. One of the constructor which we can use is,
PrintWriter supports the print( ) and println( ) methods for all types including Object. If an argument is not a primitive type, the PrintWriter methods will call the objects toString( ) method and then print out the result.
Example
16
// Demonstrate PrintWriter. import java.io.*; public class PrintWriterDemo { public static void main(String args[]) { PrintWriter pw=new PrintWriter(System.out, true);
int i = 10;
double d = 123.65; pw.println("Using a PrintWriter."); pw.println(i); pw.println(d); pw.println(i + " + " + d + " is " + (i+d)); } }
To create a byte stream linked to a file, use FileInputStream or FileOutputStream. To open a file, simply create an object of one of these classes, specifying the name of the file as an argument to the constructor.
When you are done with a file, you should close it by calling close( ).
To read from a file, you can use a version of read( ) that is defined within FileInputStream.
Each time it is called, read( ) reads a single byte from the file and returns it as an integer value. It returns 1 when the end of the file is encountered.
Example
19
import java.io.*; class ShowFile { public static void main(String args[]) throws IOException { int i; FileInputStream fin; try { fin = new FileInputStream(args[0]);
}
catch(FileNotFoundException e) { System.out.println("File Not Found"); return; }
20
catch(ArrayIndexOutOfBoundsException e) { System.out.println("Usage: ShowFile File"); return; } // read characters until EOF is encountered do { i = fin.read(); if(i != -1) System.out.print((char) i); } while(i != -1); fin.close(); }
21
Although byteval is declared as an integer, only the low-order 8 bits are written to the file.
Example
22
import java.io.*; class CopyFile { public static void main(String args[]) throws IOException {
int i;
FileInputStream fin; FileOutputStream fout; try { // open input file try { fin = new FileInputStream(args[0]); }
23
catch(FileNotFoundException e) { System.out.println("Input File Not Found"); return; } try { } catch(FileNotFoundException e) { // open output file fout = new FileOutputStream(args[1]);
24
// Copy File
try { do { i = fin.read();
if(i != -1)
fout.write(i); } while(i != -1); }
25
}
}
FileWriter(String fileName) throws IOException FileWriter(String fileName, boolean append) throws IOException
The FileReader class creates a Reader that you can use to read the contents of a file.
FileWriter
27
import java.io.*; class FWDemo { public static void main(String args[]) throws IOException{
String str;
FileWriter fw; BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
fw = new FileWriter("test.txt"); } catch(IOException exc) {
28
}
System.out.println("Enter text stop to quit"); do { System.out.print(": "); str = br.readLine(); if(str.compareTo("stop") == 0) break; str = str + "\r\n"; // add newline
fw.write(str);
} while(str.compareTo("stop") != 0); fw.close(); }
FileReader
29
import java.io.*; class FRDemo{ public static void main(String args[]) throws Exception { FileReader fr = new FileReader("test.txt"); BufferedReader br = new BufferedReader(fr); String s; while((s = br.readLine()) != null) { System.out.println(s); } fr.close(); }