我正在進行一項練習,我必須在Java中按字符複製文件字符。我用下面的文件工作:在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
寫入相應的字符。我在這裏做錯了什麼?
順便說一句,爲什麼'新的PrintWriter(新的BufferedWriter(新的FileWriter'?'新的BufferedWriter(新的FileWriter'或'新的FileWriter'就足夠了) –
@ArnaudDenoyelle每個級別都會提高作者對象的效率。 –