手机站
网通分站
电信主站
密 码:
用户名:
当前位置 : 主页>程序设计>Java技术>列表

彻底明白 Java 语言中的IO系统

来源:互联网 作者:west263.com 时间:2008-02-23
西部数码-全国虚拟主机10强!40余项虚拟主机管理功能,全国领先!双线多线虚拟主机南北访问畅通无阻!免费赠送企业邮局,.CN域名,自助建站480元起,免费试用7天,满意再付款! P4主机租用799元/月.月付免压金!

 int c;
 while((c = in2.read()) != -1)
 System.out.println((char)c);
 in2.close();
 //3. 从内存取出格式化输入
 try{
  DataInputStream in3 =new DataInputStream(new ByteArrayInputStream(s2.getBytes()));
  while(true)
   System.out.println((char)in3.readByte());
 }
 catch(EOFException e){
  System.out.println("End of stream");
 }
 //4. 输出到文件
 try{
  BufferedReader in4 =new BufferedReader(new StringReader(s2));
  PrintWriter out1 =new PrintWriter(new BufferedWriter(new FileWriter("F:\\nepalon\\ TestIO.out")));
  int lineCount = 1;
  while((s = in4.readLine()) != null)
   out1.println(lineCount ":" s);
   out1.close();
   in4.close();
 }
 catch(EOFException ex){
  System.out.println("End of stream");
 }
 //5. 数据的存储和恢复
 try{
  DataOutputStream out2 =new DataOutputStream(new BufferedOutputStream(
   new FileOutputStream("F:\\nepalon\\ Data.txt")));
  out2.writeDouble(3.1415926);
  out2.writeChars("\nThas was pi:writeChars\n");
  out2.writeBytes("Thas was pi:writeByte\n");
  out2.close();
  DataInputStream in5 =new DataInputStream(
   new BufferedInputStream(new FileInputStream("F:\\nepalon\\ Data.txt")));
   BufferedReader in5br =new BufferedReader(new InputStreamReader(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 = new RandomAccessFile("F:\\nepalon\\ rtest.dat", "rw");
 for(int i=0; i <10; i )
  rf.writeDouble(i*1.414);
  rf.close();
  rf = new RandomAccessFile("F:\\nepalon\\ rtest.dat", "r");
  for(int i=0; i <10; i )
   System.out.println("Value " i ":" rf.readDouble());
   rf.close();
   rf = new RandomAccessFile("F:\\nepalon\\ rtest.dat", "rw");
   rf.seek(5*8);
   rf.writeDouble(47.0001);
   rf.close();
   rf = new RandomAccessFile("F:\\nepalon\\ rtest.dat", "r");
   for(int i=0; i <10; i )
    System.out.println("Value " i ":" rf.readDouble());
    rf.close();
  }
 }
  关于代码的解释(以区为单位):

  1区中,当读取文件时,先把文件内容读到缓存中,当调用in.readLine()时,再从缓存中以字符的方式读取数据(以下简称“缓存字节读取方式”)。

  1b区中,由于想以缓存字节读取方式从标准IO(键盘)中读取数据,所以要先把标准IO(System.in)转换成字符导向的stream,再进行BufferedReader封装。

  2区中,要以字符的形式从一个String对象中读取数据,所以要产生一个StringReader类型的stream。

文章整理:西部数码--专业提供域名注册虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!