Java I/O流

Anu*_*dey 0 java java-io

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

   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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Rob*_*bAu 5

每次用一个字节覆盖文件.

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