【问题标题】:How to make a copy of a file containing images and text using java如何使用java制作包含图像和文本的文件的副本
【发布时间】:2015-12-14 03:49:49
【问题描述】:

我有一些 word 文档和 excel 表,其中包含一些图像以及文件文本内容。我想创建该文件的副本并将其保存在特定位置。我尝试了以下在指定位置创建文件的方法,但文件已损坏且无法读取。

InputStream document = Thread.currentThread().getContextClassLoader().getResourceAsStream("upgradeworkbench/Resources/Upgrade_TD_Template.docx");
    try {
        OutputStream outStream = null;
        Stage stage = new Stage();
        stage.setTitle("Save");
        byte[] buffer= new byte[document.available()];
        document.read(buffer);
        FileChooser fileChooser = new FileChooser();
        fileChooser.setInitialFileName(initialFileName);
        if (flag) {
            fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Microsoft Excel Worksheet", "*.xls"));
        } else {
            fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Microsoft Word Document", "*.docx"));
        }
        fileChooser.setTitle("Save File");
        File file = fileChooser.showSaveDialog(stage);
        if (file != null) {
            outStream = new FileOutputStream(file);
            outStream.write(buffer);
    //                            IOUtils.copy(document, outStream);
        }
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    }

谁能给我建议任何不同的方法来获取正确的文件。

PS:我正在使用 InputStream 读取文件,因为它位于项目 jar 中。

PPS:我也试过Files.copy(),但没用。

【问题讨论】:

标签: java file file-io inputstream


【解决方案1】:

我建议你永远不要相信InputStream.available 知道输入的实际大小,因为它只是返回准备好从缓冲区中立即读取的字节数。它可能会返回一个小数字,但并不意味着文件很小,而是缓冲区暂时半满。

完全读取 InputStream 并将其写入 OutputStream 的正确算法如下:

int n;
byte[] buffer=new byte[4096];
do
{
    n=input.read(buffer);
    if (n>0)
    {
        output.write(buffer, 0, n);
    }
}
while (n>=0);

【讨论】:

  • 它工作正常。甚至图像现在都来了。谢谢。
【解决方案2】:

您可以使用Files.copy() 方法。

将输入流中的所有字节复制到文件中。返回时,输入流将位于流的末尾。

【讨论】:

  • 我试过了,但它不能接受 StandardCopyOption 作为 CopyOption。你能建议我用什么来代替 CopyOptions 吗?
  • 错误信息描述了这个问题:你传递一个文件作为第二个参数,它需要一个路径。
  • file 替换为file.toPath()
  • 谢谢我错过了这一点。但我的问题仍然存在。我的新文件仍然没有正确创建。尺寸也较小,而且内容不可读。
【解决方案3】:

用途:

Files.copy(document, file.toPath(), StandardCopyOption.REPLACE_EXISTING);

正如班级所说,第二个参数是路径,而不是文件。

一般来说,因为现在是 2015 年,所以使用 Path 和 drop File;如果 API 仍然使用 File,请使其在最后一刻使用它并一直使用 Path。

【讨论】:

  • 我试过这种方式,但它仍然给出一个损坏的文件。
猜你喜欢
  • 2017-06-30
  • 2013-12-23
  • 1970-01-01
  • 2013-10-03
  • 1970-01-01
  • 1970-01-01
  • 2020-04-27
  • 2012-03-06
  • 1970-01-01
相关资源
最近更新 更多