グアバ–ファイルへの書き込み、ファイルからの読み取り
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を使用してappend to an existing fileを実行することもできることに注意してください。
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 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.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 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として使用することもできます。
次の例では、2つのファイルを読み取ります。最初のファイルには「Hello world」が含まれ、もう1つのファイルには「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を使用してファイルから読み取る
次に、中間のFileReaderを介して、CharStreamsを使用してファイルの内容を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()を使用してstart reading bytes after specific offsetを実行することもできます。
@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.asCharSource()を使用して、このByteSourceのCharSourceビューを取得できることに注意してください。 __
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. 結論
このクイックチュートリアルでは、read and write Files using the Guava IOのサポートとユーティリティのさまざまな方法を説明しました。
これらすべての例とコードスニペットcan be found in my Guava github projectの実装–これはEclipseベースのプロジェクトであるため、そのままインポートして実行するのは簡単です。