程序可将一个文件的数据复制到另一个文件中15次

时间:2018-11-08 06:16:56

标签: java file inputstream outputstream

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class JavaCopyFile {

    public static void main(String[] args) throws InterruptedException, IOException {


        int i=0,count=0;;
        while(i<15) {
        File source = new File("error.txt");
        File dest = new File("criteria.txt");

        // copy file conventional way using Stream
        //long start = System.nanoTime();
        copyFileUsingStream(source, dest);
        //System.out.println("Time taken by Stream Copy = " + (System.nanoTime() - start));

        if(i<15) {

            count++;
        }
        i++;
    }
        System.out.println(count);
    }
    private static void copyFileUsingStream(File source, File dest)

            throws IOException {

        InputStream input = null;

        OutputStream output = null;

        try {

            input = new FileInputStream(source);

            output = new FileOutputStream(dest);

            byte[] buf = new byte[1024];

            int bytesRead;

            while ((bytesRead = input.read(buf)) > 0) {

                output.write(buf, 0, bytesRead);

            }

        }catch(Exception e) {
            System.out.println("File not found exception");/*finally {

            input.close();

            output.close();
*/
        }

    }

}

我如上所述编写了代码-为了进行测试,我设置了count变量。 count给予15完美。但是文件仅复制一次。我要将文件复制15次到相同的目标文件。请帮我解决这个问题。我是Java编程的初学者。

1 个答案:

答案 0 :(得分:0)

如评论中所建议,您的逻辑是正确的,但是每次都在重新写入目标文件。

使用变量i表示要写入新目标文件的每个tiem,如下所示:

File dest = new File("criteria" + i + ".txt");

这将在目标位置创建15个文件,从而避免了重写相同的目标位置。


编辑:

根据您的最新评论,将代码更改如下:

public static void main(String[] args) throws InterruptedException, IOException {
    int i = 0, count = 0;
    File source = new File("error.txt");
    File dest = new File("criteria.txt");
    OutputStream output = new FileOutputStream(dest);
    while (i < 15) {
        copyFileUsingStream(source, output);
        if (i < 15) {
            count++;
        }
        i++;
    }
    System.out.println(count);
}

private static void copyFileUsingStream(File source, OutputStream output) 
  throws IOException {
    InputStream input = null;
    try {
        input = new FileInputStream(source);
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buf)) > 0) {
            output.write(buf, 0, bytesRead);
        }
    } catch (Exception e) {
        System.out.println("File not found exception");
    }
}

与其在循环的每次迭代中创建OutputStream,而是将其创建一次,然后每次将其传递给copyFileUsingStream,以便保持先前的流。