Java当中的IO(2)

1、大文件的读写方法

代码: 

//第一步:导入类
import java.io.*;

class Test{
    public static void main(String args[]){
        //声明输入流引用
        FileInputStream fis = null;
        //声明输出流引用
        FileOutputStream fos = null;
        try{
            //生成代表输入流的对象
            fis = new FileInputStream("e:/src/from.txt");
            //生成代表输出流的对象
            fos = new FileOutputStream("e:/src/to.txt");
            
            //生成一个字节数组,每次读取1024字节
            byte[] buffer = new byte[1024];
            while(true){
                //调用输入流对象的read方法,读取数据
                int temp = fis.read(buffer,0,buffer.length);
                if(temp==-1){
                    break;
                }
                //调用输出流对象的write方法,写入数据
                fos.write(buffer,0,temp);
            }
        }
        catch(Exception e){
            System.out.println(e);
        }
        finally{
            try{
                //关闭输入、输出流
                fis.close();
                fos.close();
            }
            catch(Exception e){
                System.out.println(e);
            }
        }
    }
}

2、字符流的使用方法:

  字符流:读写文件时,以字符为基础

  字符输入流:Reader <-- FileReader

    int read(char[] c,int off,int len)

  字符输出流:Writer  <-- FileWriter

    void write(char[] c,int off,int len)

代码:

//第一步,导入类
import java.io.*;

class TestChar{
    public static void main(String args[]){
        //声明一个输入字符流的引用
        FileReader fr = null;
        //声明一个输出字符流的引用
        FileWrter  fw = null;
        try{
            //生成对象
            fr = new FileReader("e:/src/from.txt");
            fw = new FileWriter("e:/src/to.txt");
            
            //声明一个字符数组
            char []  buffer = new char[100];
            int temp = fr.read(buffer,0,buffer.length);
            fw.write(buffer,0,temp);
        }catch(Exception e){
            System.out.println(e);
        }
        finally{
            try{
                fr.close();
                fw.close();
            }catch(Exception e){
                System.out.println(e);
            }
        }
    }
}

 

posted @ 2013-07-27 12:04  莫道  阅读(202)  评论(0编辑  收藏  举报