17
loading...
This website collects cookies to deliver better user experience
String
.import static java.nio.charset.StandardCharsets.UTF_16;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ReadingAllContent {
public static void main(String... args) {
try {
Path path = Paths.get("text.txt");
byte[] bytes = Files.readAllBytes(path);
String content = new String(bytes, UTF_16);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Files#readString
:Path path = Path.of("text.txt");
String content = Files.readString(path, UTF_16);
String
usando o método Files#readAllLines
.Path path = Paths.get("text.txt");
List<String> lines = Files.readAllLines(path, UTF_16);
lines.forEach(System.out::println);
Files#lines
que retorna uma Stream
que lê as linhas conforme é consumida.import static java.nio.charset.StandardCharsets.UTF_16;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class ReadingAsStream {
public static void main(String... args) {
Path path = Paths.get("text.txt");
try (Stream<String> stream = Files.lines(path, UTF_16)) {
stream.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Stream
retornada precisa ser fechada quando não for mais útil, por isso, no exemplo eu utilizei o try-with-resource que garante seu fechamento.String
em um arquivo.import static java.nio.charset.StandardCharsets.UTF_16;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class WritingString {
public static void main(String... args) {
try {
Path path = Paths.get("text.txt");
String content = "abc";
byte[] bytes = content.getBytes(UTF_16);
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Files#writeString
.Path path = Path.of("text.txt");
Files.writeString(path, "abc", UTF_16);
Path path = Paths.get("text.txt");
List<String> lines = Arrays.asList("a", "b", "c");
Files.write(path, lines, UTF_16);
String
da lista será escrita como uma nova linha no arquivo.Charset
UTF-16 explicitamente apenas para mostrar que é possível, pois nem sempre é necessário.Files#readString
, por exemplo, poderia ser invocado assim:Path path = Paths.get("text.txt");
String content = Files.readString(path);
Path path = Paths.get("text.txt");
String a = Files.readString(path);
List<String> b = Files.readAllLines(path);
Stream<String> c = Files.lines(path);
Files.writeString(path, "abc");
Files.write(path, Arrays.asList("a", "b", "c"));
String#getBytes
, se o charset não for passado explicitamente, será usado o charset padrão da sua plataforma. Para obter o charset padrão, você pode usar o método abaixo:Charset charset = Charset.defaultCharset();
StandardCharsets
possui constantes apenas para os charsets que são requeridos por qualquer implementação da plataforma Java. Se você precisar de um charset não definido nesta classe, é possível obter da seguinte forma:Charset charset = Charset.forName("UTF-32");
Charset
será retornada, caso contrário uma exceção será lançada.Files#writeString
e Files#write
também aceitam opções extras.import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.CREATE_NEW;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class WritingWithOptions {
public static void main(String... args) throws IOException {
byte[] content = "abc".getBytes();
/* 1 */ Files.write(Paths.get("a.txt"), content, APPEND);
/* 2 */ Files.write(Paths.get("b.txt"), content, CREATE, APPEND);
/* 3 */ Files.write(Paths.get("c.txt"), content, CREATE_NEW);
}
}
content
à um arquivo existente e lançará uma exceção caso o arquivo não exista.StandardOpenOption
, consulte a documentação para saber mais.