JAVA基础(五)IO(二)

上一次总结了使用字节流对文件进行读写,然而现实使用中,我们常常会进行的是大文件的读写,那么此时使用上节课的方式进行读写就不太好,因为你会不知道文件的大小,所以我们可以使用循环配合字节流来对文件进行读写:

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

class Test{
    public static void main(String args[]){
        //声明输入流引用
        FileInputStream fis = null;
        //声明输出流引用
        FileOutputStream fos = null;
        try{
            //生成代表输入流的对象
            fis = new FileInputStream("d:/work/src/from.txt");
            //生成代表输出流的对象
            fos = new FileOutputStream("d:/work/src/to.txt");
            //生成一个字节数组
            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);
            }
        }
    }
}

然后介绍一下字符流,字符流和字节流并没有什么区别,只是对文件的读取方式是用字符的形式而已,具体代码如下:

import java.io.*;

public class TestChar{
    public static void main(String argsp[]){
        FileReader fr = null;
        FileWriter fw = null;
        try{
            fr = new FileReader("d:/work/src/from.txt");
            fw = new FileWriter("d:/work/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);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值