栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java IO(2) 字节流 FileInputStream和FileOutputStream实现文件拷贝

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java IO(2) 字节流 FileInputStream和FileOutputStream实现文件拷贝

一、FileInputStream

FileInputStream可以按照字节的单位处理文件。

1 构造方法

2 方法

二、FileOutputStream 1 构造方法
FileOutputStream(File file)创建文件输出流以写入由指定的 File对象表示的文件。目标文件存在会覆盖原内容。
FileOutputStream(File file, boolean append)append=true表示文件目标文件存在继续追加内容。
FileOutputStream(FileDescriptor fdObj)创建文件输出流以写入指定的文件描述符,表示与文件系统中实际文件的现有连接。
FileOutputStream(String name)创建文件输出流以指定的名称写入文件。
FileOutputStream(String name, boolean append)创建文件输出流以指定的名称写入文件。 append=true表示文件目标文件存在继续追加内容。
2 方法

三、实现文件拷贝 1 每次读取1个字节
@Test
@DisplayName("使用字节流,每次读取1个字节")
public void testFileInputStream() throws IOException {
    String inputImgPath = "src/main/resources/static/test1.jpg";
    String outputImgPathFor = "src/main/resources/static/test2.jpg";
    File inputImgFile = new File(inputImgPath);
    File outputImgFile = new File(outputImgPathFor);
    int readData = 0;
    try (InputStream is = new FileInputStream(inputImgFile);
         OutputStream os = new FileOutputStream(outputImgFile)
    ) {
        while ((readData = is.read()) != -1) {
            os.write(readData);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
2 每次读取字节数组
@Test
@DisplayName("使用字节流,每次读取1024个字节")
public void testFileInputStreamWithByteArray() throws IOException {
    String inputImgPath = "src/main/resources/static/test1.jpg";
    String outputImgPathFor = "src/main/resources/static/test2.jpg";
    File inputImgFile = new File(inputImgPath);
    File outputImgFile = new File(outputImgPathFor);
    int readLength = 0;
    byte[] bytes = new byte[1024];
    try (InputStream is = new FileInputStream(inputImgFile);
         OutputStream os = new FileOutputStream(outputImgFile)
    ) {
        while ((readLength = is.read(bytes)) != -1) {
            os.write(bytes, 0, readLength);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/844874.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号