Goiaba - Gravar no arquivo, ler do arquivo
1. Visão geral
Neste tutorial, aprenderemos como gravar em um arquivo e, em seguida, como ler um arquivo usandoGuava IO. Discutiremos como gravar no arquivo.
2. Escreva usandoFiles
Vamos começar com um exemplo simples para escrever umString em um arquivo usandoFiles:
@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);
}
Observe que também podemosappend to an existing file usando a APIFiles.append().
3. Gravar no arquivo usandoCharSink
A seguir - vamos ver como escrever umString no arquivo usandoCharSink. No exemplo a seguir - obtemos umCharSink de um arquivo usandoFiles.asCharSink() e então o usamos para escrever:
@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);
}
Também podemos usarCharSink para gravar várias linhas em um arquivo. No exemplo a seguir - escrevemos umList de nomes e usamos um espaço como separador de linha:
@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. Gravar no arquivo usandoByteSink
Também podemos escrever bytes brutos usandoByteSink. No exemplo a seguir - obtemos umByteSink de um arquivo usandoFiles.asByteSink() e então o usamos para escrever:
@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);
}
Observe que podemos nos mover entre aByteSinkeCharSink usando a conversão simplesbyteSink.asCharSink().
5. Ler do arquivo usandoFiles
A seguir - vamos discutir como ler um arquivo usando arquivos.
No exemplo a seguir - lemos todo o conteúdo de um arquivo usando oFiles.toString(): simples
@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);
}
Também podemos ler o arquivo emList de linhas, como no exemplo a seguir:
@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"));
}
Observe que podemos usarFiles.readFirstLine() para ler apenas a primeira linha de um arquivo.
6. Ler do arquivo usandoCharSource
A seguir - vamos ver como ler um arquivo usando Charsource.
No exemplo a seguir - obtemos umCharSource de um arquivo usandoFiles.asCharSource() e usamos para ler todo o conteúdo do arquivo usandoread():
@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);
}
Também podemos concatenar dois CharSources e usá-los como umCharSource.
No exemplo a seguir - lemos dois arquivos, o primeiro contém “Hello world” e o outro contém “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. Ler do arquivo usandoCharStreams
Agora - vamos ver como ler o conteúdo de um arquivo em umString usandoCharStreams, por meio de umFileReader intermediário:
@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. Ler do arquivo usandoByteSource
Podemos usarByteSource para o conteúdo do arquivo no formato de byte bruto - como no exemplo a seguir:
@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));
}
Também podemosstart reading bytes after specific offset usandoslice() como no exemplo a seguir:
@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));
}
Observe que podemos usarbyteSource.asCharSource() para obter uma visualizaçãoCharSource desteByteSource. __
9. Ler do arquivo usandoByteStreams
A seguir - vamos ver como ler o conteúdo de um arquivo em uma matriz de bytes bruta usandoByteStreams; usaremos umFileInputStream intermediário para realizar a conversão:
@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. Ler usandoResources
Finalmente - vamos ver como ler arquivos que existem no classpath - usando o utilitárioResources como no exemplo a seguir:
@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. Conclusão
Neste tutorial rápido, ilustramos as várias maneiras deread and write Files using the Guava IO suporte e utilitários.
A implementação de todos esses exemplos e fragmentos de códigocan be found in my Guava github project - este é um projeto baseado no Eclipse, portanto, deve ser fácil de importar e executar como está.