長いメモを効率的に扱う
ユーザーがより長いメモを書くようになると、パフォーマンスが重要になります。Java のバッファ付きクラスを使うと、大きなテキストの読み書きを効率化できます。この演習では、"note.txt" に保存されたメモを処理するために BufferedReader と BufferedWriter を使います。
必要な java.io のパッケージはすべてインポート済みです。
この演習はコースの一部です
Java の入出力とストリーム
演習の手順
- ファイル
"note.txt"に対してFileWriterをラップし、BufferedWriterのインスタンスbwを作成します。 - 最初の行
"This is the first line"をファイルに書き込み、.newLine()で改行を追加してから、2行目"This is the second line"を書き込みます。 - ファイル
"note.txt"を読み込むために、FileReaderをラップしてBufferedReaderのインスタンスbrを作成します。 - ファイルを1行ずつ読み込みます。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
public class FileOperations {
public static void main(String[] args) {
try {
// Create a new instance of BufferedWriter
BufferedWriter bw = ____ ____(new FileWriter("note.txt"));
// Write the text, "This is the first line"
bw.____("This is the first line");
// Add a new line
bw.____();
// Write the second line of text, "This is the second line"
bw.____("This is the second line");
bw.close();
// Create a new instance of BufferedReader
BufferedReader br = ____ ____(new FileReader("note.txt"));
String line;
while ((line = br.____()) != null) {
System.out.println(line);
}
// Close the BufferedReader
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}