温馨提示×

Java中inputstream转file怎么实现

小亿
710
2024-03-01 19:38:12
栏目: 编程语言

可以通过以下方法将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的功能。

0