【问题标题】:Write InputStream to a file [duplicate]将 InputStream 写入文件 [重复]
【发布时间】:2016-12-22 04:03:25
【问题描述】:

我有一个对象,在这个对象中我有一个包含文件的 InputStream。

我想将 InputStream 中的内容写入文件夹中的文件。

我将如何在 Core Java 中执行此操作?

我能够使用 BufferedReader 和 .readLine() 打印出 InputStream 的每一行,但是我希望将整个文件写入磁盘,而不仅仅是其中的内容。

希望这是有道理的,谢谢。

【问题讨论】:

  • 请添加您目前尝试过的代码。

标签: java file inputstream


【解决方案1】:

如果您使用的是 Java 7 或更高版本,则可以使用java.nio.file.Files

InputStream in = obj.getInputStrem();
Path file = ...;
Files.copy(in, path);

它还支持不同的选项(参见CopyOption 实现,如StandardCopyOptionLinkOption

【讨论】:

    【解决方案2】:

    很确定它已经在那里了,你可以谷歌它。但是当您询问写入文件夹内的文件时,假设 InputStream 变量名为“input”:

    FileOutputStream output = null;
    try {
        // Create folder (if it doesn't already exist)
        File folder = new File("<path_to_folder>\\<folder_name>");
        if (!folder.exists()) {
            folder.mkdirs();
        }
        // Create output file
        output = new FileOutputStream(new File(folder, "<file_name>"));
        // Write data from input stream to output file.
        int bytesRead = 0;
        byte[] buffer = new byte[4096];
        while ((bytesRead = input.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
    } catch (IOException ioex) {
        ioex.printStackTrace();
    } finally {
        try {
            if (output != null) {
                output.close();
            }
        } catch (IOException ioex) {
            ioex.printStackTrace();
        }
        // Also close InputStream if no longer needed.
        try {
            if (input != null) {
                input.close();
            }
        } catch (IOException ioex) {
            ioex.printStackTrace();
        }
    }
    

    【讨论】:

    • 写的所有内容都包括文件图标等...还是只是文件的内容?我做了谷歌,但我对这一切感到困惑,我已经好几个月没有在这里问过问题了。
    • 它将写入包括图标在内的所有内容,但是:&lt;file_name&gt; 必须包括图标的扩展名,例如对于文本文件,“mytextfile.txt”或对于 mp3 音频文件,“@987654325 @”等
    • 另外,&lt;path_to_folder&gt; 例如C:\\Users\\&lt;Username&gt;\\Desktop&lt;folder_name&gt; 例如MyFolder
    猜你喜欢
    • 2016-03-19
    • 2012-04-25
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 2016-07-20
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多