gpt4 book ai didi

java - 使用扫描仪类java复制文件

转载 作者:行者123 更新时间:2023-12-01 13:50:33 26 4
gpt4 key购买 nike

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

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

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

有人能看出我做错了什么吗?

谢谢。

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();

}

}

最佳答案

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

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();
}

关于java - 使用扫描仪类java复制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19995279/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com