如何使用 java 复制包含图像和文本的文件

How to make a copy of a file containing images and text using java

我有一些 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()但是没用

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

Copies all bytes from an input stream to a file. On return, the input stream will be at end of stream.

使用:

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

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

一般来说,因为这是 2015 年,所以使用 Path 和 drop File;如果 API 仍然使用 File,让它在最后可能的时刻使用它,并一直使用 Path。

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

完全读取 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);