Java当中的IO(一)

1. I/O操作的目标

2. I/O的分类方法

3. 读取文件和写入文件的方法

 

1. I/O操作的目标

    从数据源当中读取数据 ,以及将数据写入到数据目的地当中

             

2. I/O的分类方法  (了解下就可) 

            

3. 读取文件和写入文件的方法

       Java里面的所有的东西  都是对象,    异常、I/O流都是对象!

       字节流的核心类:FileInputStream是上面的子类

      

        InputStream:

            int read(byte[] b, int off, int len ) 返回读取的字节数

        OutputStream:

            void write(byte[] b, int off, int len )

新建 from.txt 文本编辑存入abcd四个字符

新建 to.txt

目标将from.txt文件内容存到to.txt

 1 import java.io.*;
 2 
 3 class Test{
 4     public static void main(String args []){
 5         FileInputStream fis = null ;
 6         try{
 7             fis = new FileInputStream("e:/Java/src/IO1/from.txt");   //这一句可能会异常
 8             byte [] buffer = new byte[100];
 9             fis.read(buffer,0,buffer.length);
10             for(int i=0; i < buffer.length; i++){
11                 System.out.println(buffer[i]);
12             }
13         }
14         catch(Exception e){
15             System.out.println(e);
16         }
17     }
18 }

     abcd 的 ASCII码分别是 97 98 99 100 

     将字符转换为ASCII码, 以字节的形式读取进来

         

     因为只有4个字节, 所以后面全部是0, 调用String对象的trim方法将去除掉字符串的首尾字符和空字符

 1 import java.io.*;
 2 
 3 class Test{
 4     public static void main(String args []){
 5         FileInputStream fis = null ;
 6         try{
 7             fis = new FileInputStream("e:/Java/src/IO1/from.txt");   //这一句可能会异常
 8             byte [] buffer = new byte[100];
 9             fis.read(buffer,0,buffer.length);
10             String s = new String(buffer) ;
11             s = s.trim();
12             System.out.println(s);
13         }
14         catch(Exception e){
15             System.out.println(e);
16         }
17     }
18 }

                  

关于读写文件

 1 import java.io.*;
 2 
 3 class Test{
 4     public static void main(String args []){
 5         FileInputStream fis = null ;
 6         FileOutputStream fos = null ; 
 7         try{
 8             fis = new FileInputStream("e:/Java/src/IO1/from.txt");   //这一句可能会异常
 9             fos = new FileOutputStream("e:/Java/src/IO1/to.txt"); 
10             byte [] buffer = new byte[100];
11             int temp = fis.read(buffer,0,buffer.length);
12             fos.write(buffer,0,temp);
13         }
14         catch(Exception e){
15             System.out.println(e);
16         }
17     }
18 }

 

 

 

  

    

 

 

posted @ 2014-05-21 10:27  Mirrorhanman  阅读(217)  评论(0)    收藏  举报