私はJavaでファイルごとにファイルをコピーする必要がある練習に取り組んでいます。問題は、私は私のコードを実行した後、copy.txt
は空のままということですHamlet.txt
の文字コピーによって文字が含まれますcopy.txt
と呼ばれ、私は2番目のファイルを作成ファイルを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 ?
:私は、次のファイルで働いています。
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();
}
}
だから私はBufferedReader
オブジェクトrd
とFileWriter
オブジェクトwr
にとる方法copyFileCharByChar
を記述します。 rd
は個々の文字を読み取り、wr
は対応する文字を書き込みます。私はここで間違って何をしていますか?
ところで、なぜ'新しいPrintWriter(新しいBufferedWriter(新しいFileWriter'?'新しいBufferedWriter(新しいFileWriter'または 'new FileWriter'で十分です) –
@ArnaudDenoyelle各レベルでライターオブジェクトの効率が向上します。 –