Loading

FileInputStream和FileOutputStream

FileInputStream和FileOutputStream的使用

基本流程
  • 创建File对象
  • 创建FileInputStream或FileOutputStream对象
  • 读取数据或写入数据
  • 关闭流
注意
  • 可以处理文本文件
  • 读取中文时,一个中文可能占用多个字节,使用数组作为缓冲时,可能只有中文一部分读取到了数组中,另一部分还没有读取,打印时可能会乱码,复制不会出现问题
  • 使用构造器FileOutputStream(file)写出操作会覆盖原本的文件内容,需要使用FileOutputStream(file,true)才会在文件末尾追加
FileInputStream fis = null;
File file = null;
try {
    file = new File("hello.txt");
    fis = new FileInputStream(file);

    byte [] buffer = new byte[4];
    int len;
    while((len = fis.read(buffer))!=-1){
        String str = new String(buffer,0,len);
        System.out.print(str);
    }							
} catch (Exception e) {
    e.printStackTrace();
}finally {
    try {
        if(fis!=null){
            fis.close();
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}
/*
	原文:hello好 new world
	输出: hello�� new world
*/
复制图片
File file = null;
File file1 = null;
FileInputStream fis = null;
FileOutputStream fos = null;
try {
    file = new File("pic1.jpg");//原图片
    file1 = new File("pic2.jpg");//目的图片,可以不存在
    fis = new FileInputStream(file);
    fos = new FileOutputStream(file1);
    byte []bbuf = new byte[100];//每次读取100字节
    int len;
    while((len = fis.read(bbuf))!=-1){
        fos.write(bbuf,0,len);	//写入到目的文件中
    }
}catch (Exception e){
    e.printStackTrace();
}finally {
    try {
        if (fis!=null) {
            System.out.println("关闭输入流");
            fis.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        if(fos!=null){
            System.out.println("关闭输出流");
            fos.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
复制文件函数
public void copyFile(String srcPath,String destPath){
    File src = null;
    File dest = null;
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        src = new File(srcPath);
        dest = new File(destPath);
        fis = new FileInputStream(src);
        fos = new FileOutputStream(dest);
        byte [] buffer = new byte[1024];
        int len;
        while((len = fis.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        close(fis, fos);
    }
}
static void close(FileInputStream fis, FileOutputStream fos) {
    try {
        if (fis!=null) {
            System.out.println("关闭输入流");
            fis.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        if(fos!=null){
            System.out.println("关闭输出流");
            fos.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
posted @   7shuo  阅读(65)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示