Sie sind auf Seite 1von 29

USING I/O

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

Java 2 defines two types of streams


Byte

Streams Character Streams

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( ).

Byte Stream Classes


5

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( ).

Character Stream Classes


7

The Predefined Streams


8

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.

Reading Console Input


9

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]); } }

Writing Console Output


10

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';

// Demonstrate System.out.write(). class WriteDemo {

System.out.write(b);
System.out.write('\n'); } }

Console Input Using Character Streams


11

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

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


String str[] = new String[100]; System.out.println("Enter lines of text.");

System.out.println("Enter 'stop' to quit.");

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:");

// display the lines


for(int i=0; i<100; i++) { if(str[i].equals("stop")) break; System.out.println(str[i]); } } }

Console Output Using Character Streams


15

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(OutputStream outputStream, boolean flushOnNewline)

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)); } }

File I/O Byte Streams


17

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.

FileInputStream(String fileName)throws FileNotFoundException FileOutputStream(String fileName) throws FileNotFoundException

When you are done with a file, you should close it by calling close( ).

void close() throws IOException

Reading from File Using Byte Streams


18

To read from a file, you can use a version of read( ) that is defined within FileInputStream.

int read() throws IOException

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

Writing to File Using Byte Streams

Another most commonly used constructor is

FileOutputStream(String fileName, boolean append) throws FileNotFoundException

To write to a file, you will use the write( ) method.

void write(int byteval) throws IOException

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]);

System.out.println("Error Opening Output File");


return; }

24

catch(ArrayIndexOutOfBoundsException e) { System.out.println("Usage:CopyFile From To"); return; }

// Copy File
try { do { i = fin.read();

if(i != -1)
fout.write(i); } while(i != -1); }

25

catch(IOException e) { System.out.println("File Error"); } fin.close(); fout.close();

}
}

Execute this program by giving in command line like as follows


java CopyFile ONE.TXT TWO.TXT

File I/O Character Streams


26

FileWriter creates a Writer that you can use to write to a file.

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.

FileReader(String fileName) throws FileNotFoundException

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("Cannot open file."); return ;

}
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(); }

Das könnte Ihnen auch gefallen