File的IO总结

File分为input和output
文件的读写可以分为字节流读写,字符流读写
分别有缓冲数组读写和缓冲流读写

import java.io.*;

/**
 * Created by Administrator on 2017/3/30.
 */
public class FileTest {
    public static void main(String[] args) throws IOException {
        //copyPicture();
        readerTest();
    }
    //缓冲数组字节流复制图片
    public static void copyPicture() throws IOException {
        File oriFile = new File("E:\\1.jpg");//需要复制的文件路径
        File copyFile = new File("E:\\copy1.jpg");//需要复制到的文件路径
        FileInputStream fileInputStream = new FileInputStream(oriFile);//文件的读取通道
        FileOutputStream fileOutputStream = new FileOutputStream(copyFile);//文件的写入通道
        byte[] buf = new byte[1024];//创建一个缓冲数组用来暂时读取数据字节流
        int length = 0;
        while ((length = fileInputStream.read(buf)) != -1){
            fileOutputStream.write(buf,0,length);
        }

        fileOutputStream.close();//关闭数据流
        fileInputStream.close();
    }
    //采用缓冲字符流读取文本
    /*
    演示一下正确的IO异常的处理
     */
    public static void readerTest() throws IOException {
        BufferedReader bufferedReader = null;
        try {
            File file = new File("E:\\test.txt");
            FileReader fileReader = new FileReader(file);
            bufferedReader = new BufferedReader(fileReader);
            String content = null;
            while ((content = bufferedReader.readLine()) != null){
                System.out.println(content);
            }
        }catch (IOException e){
            System.out.println("读取文件资源出错");
            throw new RuntimeException(e);
        }finally {
            try {
                if(bufferedReader != null){
                    bufferedReader.close();
                    System.out.println("关闭资源文件成功");
                }
            }catch (IOException e){
                System.out.println("关闭资源文件失败");
                throw new RuntimeException(e);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值