Java中inputstream转file怎么实现

1214
2024/3/1 19:38:12
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

可以通过以下方法将InputStream转换为File:

import java.io.*;

public class Main {
    public static void main(String[] args) {
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            inputStream = new FileInputStream("input.txt");
            File file = new File("output.txt");
            fileOutputStream = new FileOutputStream(file);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

此代码段首先创建一个InputStream对象来读取文件内容,然后创建一个File对象来写入内容。通过读取InputStream流的内容,并将其写入到File中,实现了InputStream转换为File的功能。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java中dubbo有哪些监控手段