importjava.io.*;publicclassTestIO{publicstaticvoidmain(String[] args)throwsIOException{//1.以行为单位从一个文件读取数据 ,当读取文件时,先把文件内容读到缓存中,当调用in.readLine()时,再从缓存中以字符的方式读取数据(以下简称“缓存字节读取方式”)。BufferedReader in=newBufferedReader(newFileReader("F:\epalonTestIO.java"));String s, s2=newString();while((s=in.readLine())!=null)
s2+=s+"\\";
in.close();//1b. 接收键盘的输入 ,由于想以缓存字节读取方式从标准IO(键盘)中读取数据,所以要先把标准IO(System.in)转换成字符导向的stream,再进行BufferedReader封装。BufferedReader stdin=newBufferedReader(newInputStreamReader(System.in));
System.out.println(\"Enter a line:\");
System.out.println(stdin.readLine());//2. 从一个String对象中读取数据 , 要以字符的形式从一个String对象中读取数据,所以要产生一个StringReader类型的streamStringReader in2=newStringReader(s2);intc;while((c=in2.read())!=-1)
System.out.println((char)c);
in2.close();//3. 从内存取出格式化输入try{
DataInputStream in3=newDataInputStream(newByteArrayInputStream(s2.getBytes()));while(true)
System.out.println((char)in3.readByte());
}catch(EOFException e){
System.out.println(\"End of stream\");
}//4. 输出到文件 对String对象s2读取数据时,先把对象中的数据存入缓存中,再从缓冲中进行读取;对TestIO.out文件进行操作时,先把格式化后的信息输出到缓存中,再把缓存中的信息输出到文件中。try{
BufferedReader in4=newBufferedReader(newStringReader(s2));//把s2当作输入对象PrintWriter out1=newPrintWriter(newBufferedWriter(newFileWriter("F:\epalon TestIO.out")));intlineCount=1;while((s=in4.readLine())!=null)
out1.println(lineCount+\":\"+s);
out1.close();
in4.close();
}catch(EOFException ex){
System.out.println("End of stream");
}//5. 数据的存储和恢复 对Data.txt文件进行输出时,是先把基本类型的数据输出到缓存中,再把缓存中的数据输出到文件中;对文件进行读取操作时,先把文件中的数据读取到缓存中,再从缓存中以基本类型的形式进行读取。try{
DataOutputStream out2=newDataOutputStream(newBufferedOutputStream(newFileOutputStream("F:\epalon Data.txt")));
out2.writeDouble(3.1415926);
out2.writeChars("Thas was pi:writeChars");
out2.writeBytes("Thas was pi:writeByte");
out2.close();
DataInputStream in5=newDataInputStream(newBufferedInputStream(newFileInputStream(\"F:epalon Data.txt\")));
BufferedReader in5br=newBufferedReader(newInputStreamReader(in5));
System.out.println(in5.readDouble());
System.out.println(in5br.readLine());
System.out.println(in5br.readLine());
}catch(EOFException e){
System.out.println(\"End of stream\");
}//6. 通过RandomAccessFile操作文件RandomAccessFile rf=newRandomAccessFile("F:\epalon rtest.dat","rw");for(inti=0; i<10; i++)
rf.writeDouble(i*1.414);
rf.close();
rf=newRandomAccessFile("F:\epalon rtest.dat","r");for(inti=0; i<10; i++)
System.out.println("Value"+i+":"+rf.readDouble());
rf.close();
rf=newRandomAccessFile("F:epalon rtest.dat","rw");
rf.seek(5*8);
rf.writeDouble(47.0001);
rf.close();
rf=newRandomAccessFile("F:\epalon rtest.dat","r");for(inti=0; i<10; i++)
System.out.println("Value"+i+":"+rf.readDouble());
rf.close();
}
}