第9章 Java 7 の機能を復習する : 問題 5 : Files.readAllBytes の威力
問題
Files.readAllBytes
とFiles.write
を使って、ファイルから全ての文字を読み込み、逆順に書き出すプログラムを作成せよ。
解答
byte[] bytes = Files.readAllBytes(Paths.get("/usr/share/dict/words")); StringBuilder content = new StringBuilder( new String(bytes, StandardCharsets.UTF_8) ); content.reverse(); Files.write( Paths.get("/tmp/out.txt"), content.toString().getBytes(StandardCharsets.UTF_8) );
words ファイルの改行コードが CR+LF だと、LF, CR という順番で出てきますけどね。