0

我正在尝试使用 Scanner 类将 textfile.txt 的内容复制到 target.txt。

当我运行程序时,它会创建 target.txt 文件,但不会写入它。

我可以使用 FileInputStream 并复制文件,但我想使用 Scanner 类。

谁能看到我做错了什么?

谢谢。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Scanner;

public class ReadaFile {

    public ReadaFile() throws IOException {

        try {

            File f1 = new File("textfile.txt");
            File f2 = new File("target.txt");

            Scanner in = new Scanner(f1);
            OutputStream out = new FileOutputStream(f2);

            byte buf[] = new byte[1024];
            int i = 0;

            while (in.hasNextByte()) {

                if (in.hasNextByte() && i < buf.length) {
                    buf[i] = in.nextByte();
                    i++;
                }else{
                    out.write(buf, 0, i);
                    out.flush();
                }

            }

            in.close();
            out.close();

        } catch (FileNotFoundException e) {
            e.getMessage();
        }

    }

    public static void main(String[] args) throws IOException {
        new ReadaFile();

    }

}
4

2 回答 2

1

您根本不需要使用缓冲区数组。你可以像这样直接写字节(因为你坚持使用扫描仪,因此这个解决方案)

while (in.hasNext()) {
    out.write(in.nextLine().getBytes());
    out.write("\n".getBytes()); // This will write an extra new line character at the end of all the data.
    out.flush();
}
于 2013-11-15T07:04:59.987 回答
0

Scanner is designated to parse text data. So it's hasNextByte and nextByte methods supposed to get numbers from file and convert them to bytes. If you want to obtain a text from file you could use FileReader.

于 2013-11-15T07:18:14.250 回答