我正在进行一项练习,我必须在Java中逐个字符地复制文件。我正在使用以下文件:
Hamlet.txt
To be, or not to be: that is the question.
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles,
And by opposing end them ?
我创建了第二个文件,名为copy.txt
,其中包含Hamlet.txt
的字符副本。问题是,在我运行代码后,copy.txt
仍为空。
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class Combinations {
public void run() {
try {
BufferedReader rd = new BufferedReader(new FileReader("Hamlet.txt"));
PrintWriter wr = new PrintWriter(new BufferedWriter(new FileWriter("copy.txt")));
copyFileCharByChar(rd, wr);
}catch(IOException ex) {
throw new RuntimeException(ex.toString());
}
}
private void copyFileCharByChar(BufferedReader rd, PrintWriter wr) {
try {
while(true) {
int ch = rd.read();
if(ch == - 1) break;
wr.print(ch);
}
} catch(IOException ex) {
throw new RuntimeException(ex.toString());
}
}
public static void main(String[] args) {
new Combinations().run();
}
}
所以我写了一个方法copyFileCharByChar
,它接收BufferedReader
对象rd
和FileWriter
对象wr
。 rd
读取每个单独的字符,wr
写入相应的字符。我在这里做错了什么?
答案 0 :(得分:3)
在这种情况下你需要投射印刷品:
wr.print((char)ch);
或使用write方法:
wr.write(ch);
您还需要关闭PrintWriter:
wr.close();