0

我正在从 file1.txt 中读取行,并且仅将选定的几行复制到 file2.txt。但是java不会根据我的代码复制所有应该复制的行。不复制底部的 625 行。我必须注意,应该复制的行都显示在控制台上。所以txt文件没有问题。这里出了什么问题?代码如下:

InputStream i = new FileInputStream("file1.txt");
        InputStreamReader is=new InputStreamReader(i);
        BufferedReader bsa = new BufferedReader(iq);

        FileWriter fw=new FileWriter("file2.txt");
        BufferedWriter bw=new BufferedWriter(fw);
        PrintWriter pr=new PrintWriter(bw);

        String z="";
        for(int i=0;i<3137;i++){
            z=bsa.readLine();
            for(int q=0;q<2538;q++){
                if(array1[i].equals(array2[q])==true){
                    System.out.println(z);//to see printed lines in console
                    pr.println(z);//printing to file2
                }
            }
        }
4

3 回答 3

3

你关闭了PrintWriter吗?

pr.close();

PrintWriter缓冲数据,直到其缓冲区已满,然后写入磁盘。它的默认缓冲区大小为8192 个字符,这使得数百行在close被调用之前很容易保持未写入状态。

于 2013-03-29T23:12:02.257 回答
2

你需要关闭你的PrintWriter使用pr.close();

于 2013-03-29T23:12:16.877 回答
1

In order to copy from one file to another I would recommend this:

    try (final InputStream inputStream = new FileInputStream(file1);
            final OutputStream outputStream = new FileOutputStream(file2)) {
        final byte[] buffer = new byte[1024];
        int numRead = -1;
        while ((numRead = inputStream.read(buffer)) >= 0) {
            outputStream.write(buffer, 0, numRead);
        }
    }

It uses java 7 try-with-resources syntax; it also avoids you magic numbers.

You can also use FileChannel, this is a little simpler:

    try (final FileChannel source = new RandomAccessFile(file1, "r").getChannel();
            final FileChannel dest = new RandomAccessFile(file2, "rw").getChannel()) {
        source.transferTo(0, source.size(), dest);
    }
于 2013-03-29T23:18:03.217 回答