Download presentation
Presentation is loading. Please wait.
Published byAlan Gardner Modified over 9 years ago
1
Input & Output in Java Lecture12 Application Program JOHN DOE'S DISK
MYFILE.DAT
2
Use the standard streams System.in, System.out System.err
Objectives Perform stream input/output with the core classes in the package java.io Use the standard streams System.in, System.out System.err Distinguish between byte-oriented and character-oriented streams Write code that uses objects of the file class to navigate a file system Select valid constructor for FilterInputStream and FilterOutputStream subclasses from a list of classes in the java.io package Write appropriate code to read,write,and update files using FileInputStream,FileOutputStream,and RandomAccessFile objects
3
Based on Stream input and output
java.io Standard Java package Define classes for Input/Output Very general -Support console,files,netwoek connections,… Support raw IO, formatted IO,… The package does not provide facilities for drawing or displaying graphical components on the screen Also it does not support the mouse Based on Stream input and output i.e., raw input/output consists of a stream of bytes We just treat each byte as a binary value
4
Streams A stream is an abstraction of the continuous one-way flow of data. no inherent records or lines; no direct access to any locations
5
Input Streams vs.Output Stream
Java uses streams to facilitate input and output operations Input streams are used to “read” data Output streams are used to “write” data
6
Java I/O
7
Communications Channel
Java I/O Streams(1) Streams can also be viewed as the endpoints of a one-way communications channel, which connects an output stream to a corresponding input stream write read Communications Channel Output Stream Input Stream Everything that is written to the output stream can be read from the input stream
8
Streams can, therefore, provide a uniform interface
Java I/O Streams(2) The communications channel can be a network link, a memory buffer, a file, or a terminal to the user No matter where the information is coming from or going to and no matter what type of data is being read or written, the algorithms for reading and writing data are pretty much the same Streams can, therefore, provide a uniform interface
9
Streams are FIFO (first-in first-out)
Java I/O Streams(3) Streams are FIFO (first-in first-out) e.g., if a sequence of numbers is written to an output stream, they will be written to their destination in the same order and read from a corresponding input stream in the same order exception: RandomAccessFile Blocking I/O reads and writes must wait for the I/O operation to complete before returning
10
Characters Streams vs. Bytes Streams
The java.io package contains a collection of stream classes These classes are divided into two class hierarchies based on the data type (either characters or bytes) on which they operate
11
Bytes Stream InputStream and OutputStream are the abstract superclasses for byte streams in Java InputStream provides the API and partial implementation for input streams --streams that read 8-bit bytes OutputStream provides the API and partial implementation for output streams --streams that write 8-bit bytes These streams are typically used to read and write binary data such as images and sounds
12
Byte-Oreiented Stream Classes
13
Subclasses of InputStream and OutputStream
Object File OutputStream RandomAcessFile InputStram StreamTokenizer FileDescriptor ByteArrayOutputStream PipedOutputStream FileOutputStream FilterOutputStream PrintStream BufferedOutputStream DataOutputStream SequenceInputStream StringBufferInputStream ByteArrayInputStream PipedInputStream FileInputStream FilterInputStream LineNumberInputStream BufferedInputStream DataInputStream PushbackInputStream DataInput DataOutput
14
Predefined Stream Objects
All java programs can use three stream objects that are defined in the System class System.in is a java.io.BufferedInputStream object this object encapsulates keyboard input System.out is a java.io.PrintStream object this object encapsulates output to a command-line window and is used for most command-line mode output can redirect the output to a file System.err Output sent to System.err goes to a command line and can be mixed with output to System.out
15
Input and Output Methods
InputStream: abstract int read() throws IOException int read(byte b[]) throws IOException void close() throws IOException void available() throws IOException long skip(long n) throws IOException OutputStream: abstract void write(int b) throws IOException void write(byte[] b) throws IOException void close() throws IOException void flush() throws IOException
16
InputStream Example import java.io.*; //计算文件中的字符数和空白字符数 class CountSpace{ public static void main(String[] args) throws IOException { InputStream in; if (args.length==0) in=system.in; else in=new FileInputStream(args[0]); int ch; int total; int spaces=0; for(total=0;(ch=in.read())!=-1;total++){ if (Charater.isSpace((char)ch) spaces++; } System.out.println(total+”chars,”+spaces+”spaces”);
17
OutputStream Example(1)
import java.io.*;//将输入的数据拷贝输出,并转化特定字符 class Translate{ public static void main(String[] args){ InputStream in=System.in; OutputStream out=System.out; if (args.length!=2) error(“from/to needed”); String from=args[0], to=args[1]; int ch,i; if (from.length()!=to.length()) error(“same length needed”);
18
OutputStream Example(2)
try{ while((ch=in.read())!=-1){ if ((i=from.indexOf(ch))!=-1) out.write(to.charAt(i)); else out.write(ch); } }catch(IOException e) { error(“I/O Exception:”+e); } public static void error(String err){ System.err.print(“Translate:”+err); System.exit(1); //非零值意指“不好”
19
when you want to do more than read and write bytes and chars ...
Filtered Streams when you want to do more than read and write bytes and chars ... Stream filters provide enhanced functionality on top of other existing streams The basic approach is to layer stream filters on top of more primitive streams Filter streams add new constructors to the basic ones in the InputStream and OutputStream classes, and enable you to chain streams to produce composite streams of greater power
20
Byte-oriented Filter Streams
FilterInputStream, FilterOutputStream: DataInputStream, DataOutputStream These classes transmit data of specific types across a stream instead of treating a stream as a sequence of independent bytes.You can also call methods of these classes to read and write the binary representations of the primitives types BufferedInputStream, BufferedOutputStream These classes provide buffering for input and output operations PrintStream This class implements methods for displaying data types textually(print,println) PushbackInputStream This class maintains a one-byte push-back buffer LineNumberInputStream provides an object to keep track of line numbers while reading input
21
Data Streams and Interfaces
While reading and writing bytes is useful, there is also a frequent need to transmit data of specific types across a stream The DataInput and DataOutput interfaces defines methods to transmit Java primitive types across a stream A default implementation of each interface is provided by the classes DataInputStream and DataOutputStream
22
Basic input/output method
Read Write Type readBoolean writeBoolean boolean readChar writeChar char readByte writeByte byte readShort writeShort short readInt writeInt int readLong writeLong long readFloat writeFloat float readDouble writeDouble double readUFT writeUFT String(UTF format)
23
Other DataInput methods
public abstract void readFully(byte[] buf) throws IOException public abstract void readFully(byte[] buf,int off,int len) throws IOException public abstract int skipBytes(int n) throws IOException public abstract String readLine() throws IOException public abstract int readUnsignedByte() throws IOException public abstract int readUnsignedShort(byte[] buf) throws IOException The DataInput interface handles end-of –file by throwing an EOFException when it occurs. EOFException is an extended class of IOException
24
Other DataOutput methods
The DataOutput interface supports signatures equivalent to the three forms of write in OutputStream public abstract void writeBytes(String s) throws IOException public abstract void writeChars(String s) throws IOException DataInputStream/DataOutputStream: For each Data interface, there is a corresponding Data stream Each Data class is an extension of its Filter class, so Data streams can be used to filter other streams Constructor parameters: InputStream in/OutputStream out
25
Example int account ; String name; double balance; try { input=new DataInputStream( new FileInputStream(“client.dat”)) } catch (IOException e) { System.err.println(“Fail to open the file”+e.toString()); System.exit(1); } try { account = input.readInt(); name = input.readUTF(); balance = input.readDouble(); } catch (EOFException eof) { …} catch (IOException e) {…}
26
Buffered Streams The BufferedInputStream/BufferedOutputStream classes support objects that buffer their data to avoid every read or write going directly to the next stream When a buffered stream is created, its buffer size can be specified explicitly(InputStream in, int size),or it can use a default size[32b] (InputStream in) BufferedOutputStream behaves similar to OutputStream Example OutputStream bufferedFile(String path) //为文件提供缓冲流 throws IOException { OutputStream out=new FileOutputStream(path); return new BufferedOutputStream(out); }
27
PrintStream PrintStream is used every time a print or println method invocation appears in a program It provides print and println methods for the following types:char,int, float,object,boolean, char[],long, double, String Two Constructors: (OutputStream out) 、 (OutputStream out, boolean autoflush) If the autoflush boolean is true,writing a new line character ‘\n’ invokes flush The print(String) and print(char[]) methods are synchronized. All the other print and println methods are written in terms of these two methods,so printing on a PrintStream object is thread-safe
28
A PushbackInputStream provides single-character pushback
The pushback buffer is a protected int field named pushBack. A subclass could provoide a different way to modify this character. A value of –1 means the pushback buffer is empty. Any other value means that the PushBack.read method returns pushBack as the first byte of input Constractor parameter: (InputStream in) unread(int ch)return the int which represent a char into input stream Example: This example PushbackInputStream to find the longest sequence of any single byte in its input
29
Example(1) import java.io.*; class SequenceCount{ public static void main(String[] args){ try{PushbackInputstream in=new …(System.in); int max=0; //所找到的长序列 int maxB=-1; //构成该序列的字节 int b; //当前输入字节 do{ int cnt; int bl=in.read(); //序列中的第一个字节 for(cnt=1;(b=in.read())==b1;cnt++) continue;
30
Example(2) if (cnt>max){ max=cnt; //记下长度 maxB=b1; //记下字节的值 } in.unread(b); //回送下个序列的开始字节 }while(b!=-1); //读到输入的结束 System.out.println(max+”bytes of”+maxB); }catch(IOException e){ System.out.println(e); System.exit(1); } //当到达一个序列结尾时,下个序列的第一个字 } // 节实际已经被读入。用unread将该字节回送
31
LineNumberInputStream
The LineNumberInputStream class provides an object to keep track of line numbers while reading input The getLineNumber method returns the current line number. Line numbering starts at 1 The current line number can be set with setLineNumber. This is useful when multiple input streams are treated as one input stream,but line numbers are needed relative to each stream Example:This program prints the line number where the first instance of a particular character is found in a file To ensure that the current line number from Sysytem.in: LineNumberInputStream lnum = new LineNumberInputStream(System.in); System.in = lnum;
32
Example(1) import java.io.*; class Findchar{ public static void main(String[] args) throws Exception { if (args.length!=2) throws new Exception(“need char/ file”); int match=args[0].charAt(0); FileInputStream fileIn=new FileInputStream(args[1]); LineNumberInputStream in=new LineNumberInputStream(fileIn);
33
while((ch=in.read())!=-1){ if (ch==match){ System.out.println
Example(2) int ch; while((ch=in.read())!=-1){ if (ch==match){ System.out.println (“‘“+(char)ch+”’at line”+in.getLineNumber()); System.exit(0); } System.out.println(ch+”not found”); System.exit(1); 返回
34
Other Byte I/O Streams(1)
The java.io package defines many classes.Extensions of InputStream include the following: ByteArrayInputStream:lets you read an array of bytes as though it is an InpputStream object SequenceInputStream:provides a mechanism for concatenating the data from two or more InputStream objects into a single,seamless stream PipedInputStream:implements half a pipe and is especially useful for communication between threads StringBufferInputStream: reads from a String instead of a byte array(the same as ByteArrayInputSteam )
35
Other Byte I/O Streams(2)
Extensions of OutputStream include the following: ByteArrayOutputStream:sends its output into an object of type byte[] PipedOutputStream:is the complementary class to PipedInputStream. Together, these two classes comprise a pipe that you can use for communication between threads
36
ByteArray Streams ByteArray Streams uses a byte array as its input/output source ByteArrayInputStream public ByteArrayInputStream(byte[] buf) public ByteArrayInputStream(byte[] buf,int offset,int len) reset(): 指针移到流的开始 (2) ByteArrayOutputStream public ByteArrayOutputStream() (32 bytes) public ByteArrayOutputStream(int size) public synchronized byte[] toByteArray() public int size() public String toString(int hiByte)
37
Example String tmp = “abcdefghijklmnopqrstuvwxyz”; byte b[] = new byte [tmp.length())]; tmp.getBytes(0,tmp.length(),b,0); ByteArrayInputStream n1=new ByteArrayInputStream(b); … n2=new ByteArrayInputStream(b,0,3); // abc for (int i=0; i<2; i++) { // 打印大小写字母表 while ((c=n1.read())!=-1) if (i==0) System.out.print((char)c); else System.out.print(Character.toUpperCase(c)); System.out.println(); input.reset(); }//将读指针移到字节数组的开始
38
SequenceInputStream The SequenceInputStream class creates a single input stream from reading one or more input streams,reading the first until last Two constructors:one for the common case of two input streams;the other for any arbitrary number of input streams using the Enumeration abstraction
39
Example(1) import java.io.*; import java.util.Vector; class Sum{ public static void main(String[] args){ InputStream in; if (args.length==0){ in=System.in; }else{ InputStream stringIn; Vector inputs=new Vector(args.length); for(int i=0;i<args.length;i++){ String arg=args[i]+“ ”; stringIn = new StringBufferInputStream(arg); inputs.addElement(stringIn); }
40
Example(2) in=new SequenceInputStream(inputs.elements()); } try{ double total=sumStream(in); System.out.println(“The sum is”+total); }catch(IOException e){ System.out.println(e); System.exit(-1); //...
41
Piped Streams Bytes written on the input stream of a pair are those read on the output Piped streams are thread-safe: one for reading and one for writing Writing on one end of the pipe blocks the thread when the pipe files up If the writer and reader are the same thread, that thread blocks permanently Example: This example creates a new thread to read from the output of some data generator object that writes its output onto an OutputStream object
42
Example class Pipe{ public static void main(String[] args){ try{ PipedOutputStream out=new PipedOutputStream(); PipedInputStream in=new PipedInputStream(out); // 数据产生器将结果写入给定的输出流中 DataGenerator data=new DataGenerator(out); data.setPriority(Thread.MIN_PRIORITY); data.start(); int ch; while((ch=in.read())!=-1) System.out.print((char)ch); System.out.println(); }catch(IOException e){ System.out.println(“Exception:”+e); } } }
43
StringBufferInputStream
It provides a single constructor that is the string from which to read.Each character in the string is treated as a byte Note that StringBufferInputStream operats on String object, not StringBuffer objects There is no StringBufferOutputStream. A similar effect can be obtain by using the toString method on ByteArrayInputSteam
44
Example class Factor { public static void main(String[] args) { if (args.length = = 0) { factorNumbers(System.in); } else { InputStream in; for (int i = 0; i < args.length; i ++) { in = new StringBufferInputStream(args[i]); factorNumbers(in); } //…
45
Difference exits between files and the standard console I/O objects:
File I/O Basics Programming stream I/O to and from files is much like that to and from the console Difference exits between files and the standard console I/O objects: Before you can use a file,you must associate the file with a FileInputStream or FileOutputStream object If you want to access the data in a file in random-access order, you must open it as a RandomAccessFile In a network environment, the default security restrictions do not let applets do any file I/O on the client workstation
46
(1) FileInputStream File Streams Constructor
— A constructor that takes a String that is the name of the file — A constructor that takes a File that refers to the file — A constructor that takes a FileDescriptor object Methods: overwrite six methods of InputStream InputStream f0 = new FileInputStream(“a.bat”); File f = new File(“a.bat”); InputStream f1 = new FileInputStream(f); (2) FileOutputStream Open read-only file,signals an exception Open a file which created already,its content will be lost
47
File InputStreams Example(1)
import java.io.*; import java.util.* class FileInputDemo { public static void main(String args[]) throws Exception{ int size; InputStream f1=new FileInputStream(“file.htm”); size=f1.available(); // total size // Read the first 1/4 by read() for (int i=0; i<size/4; i++) System.out.print((char)f1.read()); System.out.println(“Still available: ”+f1.available());
48
File InputStreams Example(2)
// Read the next 1/8 by read(b[]) byte b[] = new byte[size/8]; if (f1.read(b)!=b.length) System.err.println(“Something bad happened!”); System.out.println(“Still available: ”+f1.available()); // Skip another 1/4: skip() f1.skip(size/4); f1.close(); }
49
File OutputStreams Example(1)
import java.io.* class FileOutputDemo { public static byte getInput()[] throws Exception { byte buffer[] = new byte[12]; for (int i=0;i<12;i++) buffer[i]=(byte) System.in.read(); return buffer; }
50
File OutputStreams Example(2)
public static void main(String args[]) throws Exception { byte buf[]=getInput(); OutputStream f0=new FileOutputStream(“file1.txt”); OutputStream f1=new FileOutputStream(“file2.txt”); OutputStream f2=new FileOutputStream(“file3.txt”); for (int i=0;i<12;i+=2) f0.write(buf[i]); f0.close(); f1.write(buf); f1.close(); f2.write(buf,12/4, 12/2); f2.close(); } }
51
The File Class(1) The File class provides several common manipulations that are useful with filenames. It provides methods to separate pathnames into subcomponents, and for querying the file system about the file a pathname refers to Constructors: public File(String path) :Creates a File object to manipulate the specified path.This method throws a NullPointerException if the path parameter is null public File(String dirName,String name) File(dirName + File.separator +name) public File(File fileDir,String name) File(fileDir.getPath(), name) Example: File f1=new File(“/”); File f2=new File(“/”,”autoexec.bat”); File f3=new File(f1,”autoexec.bat”);
52
The File Class(2) (2) Methods get: retrieve information about components of a File object’s pathname getName()、getPath、getAbsolutePath()、getParent() exists: returns true if the file exists in the file system canRead: returns true if the file exists and can be read canWrite: returns true if the file exists and can be written isFile: returns true if the file is a normal file isDirectory: returns true if the file is a directory isAbsolute: returns true if the path is an absolute pathname public long lastModified(): returns the last modification time
53
The File Class(3) public long length(): returns the file length in bytes public boolean mkdir(): Creates a directory, returning true on success public boolean mkdirs(): Creates all directories in this path,returning true if all were created public boolean renameTo(File new_name) : Renames a file, returning true if the rename succeeded public boolean delete() : Deletes the file or directory named in this File object, returning true if the deletion succeeded public String[] list(): Lists all files in a directory except the equivalent of “.”and “..”
54
The File Class(4) public String[] list(FilenameFilter filter) :Uses the specified filter to list files in a directory (3) Note equals:true if two file objects have the same path , not if they refer to the same underlying file system object Files are created using FileOutputStream objects or RandomAccessFile objects, not using File objects The character File.pathSeparatorChar and the string File.pathSeparator represent the character that separates file or directory names in a search path The path of the file is a protected String field named path.Classes extending File can directly access or modify it as needed
55
Example1 import java.io.*; public class CopyBytes { public static void main(String[] args) throws IOException { if(args.length != 2) throw new RuntimeException(“Usage:CopyBytes <src> <dst>”); File inputFile = new File(args[0]); File outputFile = new File(args[1]); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } }
56
public class FileOperation { public static void main(String[] args)
Example2 import java.io.*; public class FileOperation { public static void main(String[] args) {try{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String sdir = “c:\\temp”; String sfile; File Fdir1 = new File(sdir);\\创建目录c:\temp if (Fdir1.exits() && Fidir1.isDirectory()) \\目录存在 {System.out.println(“Directory” + sdir + “exits.” ); for (int I=0; I<Fdir1.list().length; I++) \\列出目录内容 System.out.println((Fdir1.list())[i] ); File Fdir2 = new File(“c:\\temp\\temp”);
57
Fdir2.mkdir(); \\目录不在则创建之 System.out.println();
Example2 if (!Fdir2.exits()) Fdir2.mkdir(); \\目录不在则创建之 System.out.println(); System.out.println(“Now the new list after create a new dir:”); for (int I=0; I<Fdir1.list().length; I++) \\检查目录是否已建立 System.out.println((Fdir1.list())[i] );} System.out.println(“Enter a file name in this directory:”); sfile = in.readLine(); File Ffile = new File(Fdir1, sfile); if (Ffile.isFile()) \\若此File对象代表文件 {System.out.println(“File” +Ffile.getName() +”in Path” +Ffile.getPath() + “is” +Ffile.getlength() +”in length.”); } }catch()…
58
RandomAccessFile(1) The “random access” referred to in the name of the class is the ability to set the read/write file pointer to any position in the file,and perform the operation You cannot use a RandomAccessFile where either an InputStream or OutputStream object required,but it supports methods of the same names and signatures as their read and write invocations RandomAccessFile implements both the DataInput and DataOutput interface, so it can be used to read and write bulit-in Java data types Constructors: public RandomAccessFile(String name,String mode) throws IOException
59
RandomAccessFile(2) public RandomAccessFile(File file,String mode) throws IOException public RandomAccessFile(FileDescriptor fd) throws IOException (2) Methods public long getFilePointer() throw IOExcepton Returns the current location of the file pointer(in bytes) from the beginning of the file public void seek(long pos) throw IOException Sets the file pointer to the specified position in number of bytes from the beginning of the file public long length() throws IOException
60
Characters Streams Reader and Writer are the abstract superclasses for character streams in java.io Reader provides the API and partial implementation for readers --streams that read 16-bit characters Writer provides the API and partial implementation for writers --streams that write 16-bit characters
61
Character Stream Classes
62
Subclasses of Reader and Writer
Object Writer Reader BufferedWriter CharArrayWriter FilterWriter OutputStreamWriter FileWriter PipedWriter PrintWriter BufferedReader CharArrayReader FilterReader PipedReader InputStreamReader StringReader PpushbackReader LineNumberReader FileReader StringWriter
63
The corresponding input/output streams(1)
Reader InputStream BufferedReader BufferedInputStream LineNumberStream LineNumberReader CharArrayReader ByteArrayInputStream (none) InputStreamReader FileInputStream FileReader FilterInputStream FilterReader PushbackInputStream PushbackReader PipedReader PipedInputStream StingReader StringBufferInputStream
64
The corresponding input/output streams(2)
Writer OutputStream BufferedWriter BufferedOutputStream CharArrayWriter ByteArrayOutputStream OutputStreamWriter (none) FileWriter FileOutputStream FilterWriter FilterOutputStream PrintWriter PrintStream PipedWriter PipedOutputStream StingWriter (none)
65
(1) function StreamTokenizer(1)
Tokenizing input data is a common application,and the java.io package provides a StreamTokenizer class for simple tokenization problems It deals only with the lower 8 bits of Unicode(’\u0000’-‘\u00FF’ ) A stream is tokenized by creatinga StreamTokenizer with an InputStream object as its source, and then setting parameter for the scan. A scanner loop invokes nextToken, which returns the token type of the next token in the stream
66
(2) Token types: StreamTokenizer(2) “ordinary”characters
“special” characters TT_WORD(-3) :A word was scanned TT_NUMBER(-2) :A number was scanned TT_EOL(‘\n’):An end-of-line was found TT_EOF(-1) : The end-of-file was reached static double sumStream(Inputstream in) throws IOException{ StreamTokenizer nums = new StreamTokenizer(in); double result = 0.0; while(nums.nextToken() ==StreamTokenizer.TT_NUMBER) result += nums.nval; return result; }
67
StreamTokenizer(3) (3) Method public void wordChars(int low,int hi) public void whitespaceChars(int low,int hi) public void ordinaryChar(int ch) public void ordinaryChars(int low,int hi) public void commentChar(int ch) public void quoteChar(int ch) public void parseNumbers() public void resetSyntax() public void eolIsSignificant(boolean flag) public void slashStarComments(boolean flag) public void slashSlashComments(boolean flag) public void lowerCaseMode(boolean flag) public void pushback() public int lineno() public String toString()
68
Example(1) Import java.io.*; Public class IODemo
Public static void main (String[] args) { try { //1.Reading input by lines: if (args.length = = 0) { BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)) ; System.out.print(“Enter a line:”); System.out.println(stdin.readLine()); stdin.close(); } else BufferedReader in = new BufferedReader(new FileReader(args[0])) ; String s, s2 = new String(); While ((s = in.readLine()) != null ) s2 += s + “\n”; in.close();
69
StringReader in2 = new StringReader (s2); int c;
Example(2) //2. Input from memory StringReader in2 = new StringReader (s2); int c; While ((c = in2.read()) != -1) System.out.print((Char)c); Note: read() returns next byte as an int, so you must cast it as a char
70
Example(3) //3. Formatted memory input try { DataInputStream in3 = new DataInputStream ( new StringBufferInputStram(s2)); while (true) System.out.print((char)in3.readByte()); } catch (EOFException e) { System.out.println(“End of stram”); }
71
Example(4) try { //4. Line numbering &file output LineNumberReader li = new LineNumberReader( new StringReader(s2)); BufferedRader in4 = new BufferedRader(li); PrintWriter out1 = new PrintWriter(new BufferedWriter( new FileWriter (“IODemo.out”))); while ((s = in4.readLine()) != null) out1.println (“Line”+ li.getLineNumber()+s); out1.close(); } catch (EOFexception e) { System.out.println(“End of stream”);}
72
Example(5) //5. Storing & recovering data try { DataOutputStream out2 = new DataOutputStream( new BufferedOutputStream (“Data.txt”))); out2.writeDouble( ); out2.writeBytes(“That was pi”); out2.close(); DataInputStream in5 = new DataInputStream ( new BufferedInputStream( new FileInputStream(“Data.txt”)));
73
Example(6) BufferedReader in5br = new BufferedReader ( new InputStreamReader(in5)); // Must use DataInputStream for data: System.out.println(in5.readDouble()); //Can now use the “proper” readLine()) System.out.println(in5br.readLine()); } catch (EOFException e) { System.out.println (“End of Stream”); }
74
Example(7) //6. Reading and Writing random access file RandomAccessFile rf = new RandomAccessFile(“rtest.dat”, “rw”); for (int i = 0; i <10 ; i++) rf.writeDouble(i*1.414); rf.close(); rf = new RandomAccessFile(“rtest.dat”, “rw”); rf.seek(5*8); rf.writeDouble( ); rf = new RandomAccessFile(“rtest.dat”, “r”);
75
Example(8) for (int i = 0; i <10 ; i++) System.out.println( “Value” + i + “:” +rf.readDouble()); rf.close(); } catch (FileNotFoundException e) { System.out.println ( “File Not Found:” + args[1]); } catch (IOException e) { System.out.println(“IO Exception”);} }
76
Homework 1.实现一个常用的词统计程序wc(统计任何输入流的字符数、行数和词数)。程序有两种状态,如果没有文件名作参数,程序就使用标准的输入流,如果有一个 或多个文件,程序就依次进行统计。 用FileInputStream实现wc程序 用PushbackInputStream实现wc程序 2. 两个线程,一个是读者,一个是写者,读者取写者所写的内容,双方约定以“.”为信息的结束符。用管道I/O类实现该程序。
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.