1概要

このチュートリアルでは – ファイルへの書き込み方法、そして

Guava IO

を使ったファイルからの読み取り方法を学びます。ファイルへの書き込み方法について説明します。


2

Files


を使って書く


Files

を使用して

String

をファイルに書き込む簡単な例から始めましょう。

@Test
public void whenWriteUsingFiles__thenWritten() throws IOException {
    String expectedValue = "Hello world";
    File file = new File("test.txt");
    Files.write(expectedValue, file, Charsets.UTF__8);
    String result = Files.toString(file, Charsets.UTF__8);
    assertEquals(expectedValue, result);
}


Files.append()

APIを使用して

既存のファイルに

追加することもできます。


3

CharSink


を使用してファイルに書き込む

次に、

CharSink

を使用して

String

をファイルに書き込む方法を見てみましょう。次の例では、

Files.asCharSink()

を使用してファイルから

CharSink

を取得し、それを使用して書き込みます。

@Test
public void whenWriteUsingCharSink__thenWritten() throws IOException {
    String expectedValue = "Hello world";
    File file = new File("test.txt");
    CharSink sink = Files.asCharSink(file, Charsets.UTF__8);
    sink.write(expectedValue);

    String result = Files.toString(file, Charsets.UTF__8);
    assertEquals(expectedValue, result);
}


CharSink

を使用してファイルに複数行を書き込むこともできます。次の例では – 名前の

List

を書き、行区切り文字としてスペースを使います。

@Test
public void whenWriteMultipleLinesUsingCharSink__thenWritten() throws IOException {
    List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
    File file = new File("test.txt");
    CharSink sink = Files.asCharSink(file, Charsets.UTF__8);
    sink.writeLines(names, " ");

    String result = Files.toString(file, Charsets.UTF__8);
    String expectedValue = Joiner.on(" ").join(names);
    assertEquals(expectedValue, result.trim());
}


4

ByteSink


を使用してファイルに書き込む


ByteSink

を使って生のバイトを書くこともできます。次の例では、

Files.asByteSink()

を使用してファイルから

ByteSink

を取得し、それを使用して書き込みます。

@Test
public void whenWriteUsingByteSink__thenWritten() throws IOException {
    String expectedValue = "Hello world";
    File file = new File("test.txt");
    ByteSink sink = Files.asByteSink(file);
    sink.write(expectedValue.getBytes());

    String result = Files.toString(file, Charsets.UTF__8);
    assertEquals(expectedValue, result);
}

単純な変換

byteSink.asCharSink()を使用して、

ByteSink



CharSink__の間を移動できることに注意してください。


5

Files


を使用してファイルから読み取る

次に、

Files

を使用してファイルから読み取る方法について説明しましょう。

次の例では、単純な__Files.toString()を使用してファイルのすべての内容を読み取ります。

@Test
public void whenReadUsingFiles__thenRead() throws IOException {
    String expectedValue = "Hello world";
    File file = new File("test.txt");
    String result = Files.toString(file, Charsets.UTF__8);

    assertEquals(expectedValue, result);
}

次の例のようにファイルを行の

List

に読み込むこともできます。

@Test
public void whenReadMultipleLinesUsingFiles__thenRead() throws IOException {
    File file = new File("test.txt");
    List<String> result = Files.readLines(file, Charsets.UTF__8);

    assertThat(result, contains("John", "Jane", "Adam", "Tom"));
}

ファイルの最初の行だけを読み込むために

Files.readFirstLine()

を使うことができることに注意してください。


6.

CharSource


を使用してファイルから読み取る

次に、CharSourceを使ってファイルから読み込む方法を見てみましょう。

次の例では、

Files.asCharSource()

を使用してファイルから

CharSource

を取得し、それを使用して

read()

を使用してすべてのファイルの内容を読み取ります。

@Test
public void whenReadUsingCharSource__thenRead() throws IOException {
    String expectedValue = "Hello world";
    File file = new File("test.txt");
    CharSource source = Files.asCharSource(file, Charsets.UTF__8);

    String result = source.read();
    assertEquals(expectedValue, result);
}

2つのCharSourceを連結して、それらを1つの

CharSource

として使用することもできます。

次の例では、最初のファイルに「

Hello world

」が含まれ、もう一方のファイルに「

Test

」が含まれています。

@Test
public void whenReadMultipleCharSources__thenRead() throws IOException {
    String expectedValue = "Hello worldTest";
    File file1 = new File("test1.txt");
    File file2 = new File("test2.txt");

    CharSource source1 = Files.asCharSource(file1, Charsets.UTF__8);
    CharSource source2 = Files.asCharSource(file2, Charsets.UTF__8);
    CharSource source = CharSource.concat(source1, source2);

    String result = source.read();
    assertEquals(expectedValue, result);
}


7.

CharStreams


を使用してファイルから読み取る

それでは、

CharStreams

を使って、中間の

FileReader

を介してFileの内容を

String

に読み込む方法を見てみましょう。

@Test
public void whenReadUsingCharStream__thenRead() throws IOException {
    String expectedValue = "Hello world";
    FileReader reader = new FileReader("test.txt");
    String result = CharStreams.toString(reader);

    assertEquals(expectedValue, result);
    reader.close();
}


8

ByteSource


を使用してファイルから読み取る

次の例のように、

ByteSource

を使用して、生のバイト形式のファイルの内容を取得できます。

@Test
public void whenReadUsingByteSource__thenRead() throws IOException {
    String expectedValue = "Hello world";
    File file = new File("test.txt");
    ByteSource source = Files.asByteSource(file);

    byte[]result = source.read();
    assertEquals(expectedValue, new String(result));
}

次の例のように

slice()

を使用して、

特定のオフセットの後に

バイトの読み込みを開始することもできます。

@Test
public void whenReadAfterOffsetUsingByteSource__thenRead() throws IOException {
    String expectedValue = "lo world";
    File file = new File("test.txt");
    long offset = 3;
    long len = 1000;

    ByteSource source = Files.asByteSource(file).slice(offset, len);
    byte[]result = source.read();
    assertEquals(expectedValue, new String(result));
}

この

ByteSource



CharSource

ビューを取得するには、

byteSource.asCharSource()

を使用できます。


9

ByteStreams


を使用してファイルから読み取る

次に、

ByteStreams

を使ってファイルの内容を生のバイト配列に読み込む方法を見てみましょう。変換を実行するために、中間の

FileInputStream

を使用します。

@Test
public void whenReadUsingByteStream__thenRead() throws IOException {
    String expectedValue = "Hello world";
    FileInputStream reader = new FileInputStream("test.txt");
    byte[]result = ByteStreams.toByteArray(reader);
    reader.close();

    assertEquals(expectedValue, new String(result));
}


10

Resources


を使って読む

最後に、次の例のように

Resources

ユーティリティを使用して、クラスパスに存在するファイルを読み取る方法を見てみましょう。

@Test
public void whenReadUsingResources__thenRead() throws IOException {
    String expectedValue = "Hello world";
    URL url = Resources.getResource("test.txt");
    String result = Resources.toString(url, Charsets.UTF__8);

    assertEquals(expectedValue, result);
}


11結論

このクイックチュートリアルでは、Guava IO

のサポートとユーティリティを使用して

ファイルを読み書きするさまざまな方法を説明しました。

これらすべての例とコードスニペットの実装はhttps://github.com/eugenp/tutorials/tree/master/guava#readme[グアバgithubプロジェクト]にあります。インポートしてそのまま実行するのは簡単なはずです。