Java I/O 流

Java I/O stream

我正在尝试使用 Java I/O 流将一个文件的内容复制到另一个文件。 我为此编写了下面的代码,但它只复制了源文件的最后一个字母。

   package io.file;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


public class FileCopyTester {

    public void copyFile() {
        FileInputStream fis = null;
        try{
            fis = new FileInputStream("resources/Source.txt");
            System.out.println("Started copying");
            int data =  fis.read();

        while (data != -1){
            try (FileOutputStream fos = new FileOutputStream("resources/Destination.docx")){
                fos.write(data);
                fos.close();
            }
            catch (IOException io) {
                System.err.println("Error o/p:"+io.getMessage());
            }
            System.out.print((char)data+" ");
            data = fis.read();
        }
        fis.close();
        System.out.println("End Copying");
        }

        catch(IOException ioe){
            System.err.println("ERROR: "+ioe.getMessage());
        }

    }

    public static void main(String[] args) {
        new FileCopyTester().copyFile();
    }
}

在源文件中我有类似的数据 22 / 7 3.142857

所以在目的地我只得到 7 请帮助如果我遗漏了一些东西,比如不应该覆盖目标文件中的数据的东西。

你每次用一个字节覆盖你的文件。

解决方案:在 while 循环外打开输出流,然后关闭它。

在循环的每一轮都打开流是没有意义的 - 新数据正在覆盖文件的旧内容。但是 - 使用 "append mode" 打开流将使您的代码工作:

FileOutputStream fos = new FileOutputStream("resources/Destination.docx", true);

第二种更好的解决方案是在循环之前打开流:

FileInputStream fis = new FileInputStream("resources/Source.txt");
FileOutputStream fos = new FileOutputStream("resources/Destination.docx");

int data = fis.read();
while (data != -1){
    fos.write(data);
    data = fis.read();
}

fos.close();