93
String content = Files.readString(path, StandardCharsets.US_ASCII);
static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, encoding); }
List<String> lines = Files.readAllLines(Paths.get(path), encoding);
try (Stream<String> lines = Files.lines(path, encoding)) { lines.forEach(System.out::println); }
String content = readFile("test.txt", StandardCharsets.UTF_8);
String content = readFile("test.txt", Charset.defaultCharset());
80
import java.io.*; import java.nio.charset.*; import org.apache.commons.io.*; public String readFile() throws IOException { File file = new File("data.txt"); return FileUtils.readFileToString(file, StandardCharsets.UTF_8); }
75
Scanner scanner = new Scanner( new File("poem.txt") ); String text = scanner.useDelimiter("\\A").next(); scanner.close(); // Put this call in a finally block
Scanner scanner = new Scanner( new File("poem.txt"), "UTF-8" ); String text = scanner.useDelimiter("\\A").next(); scanner.close(); // Put this call in a finally block
try (Scanner scanner = new Scanner( new File("poem.txt"), "UTF-8" )) { String text = scanner.useDelimiter("\\A").next(); }
68
import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; String content = new String(Files.readAllBytes(Paths.get("readMe.txt")), StandardCharsets.UTF_8);
53
private String readFile(String pathname) throws IOException { File file = new File(pathname); StringBuilder fileContents = new StringBuilder((int)file.length()); try (Scanner scanner = new Scanner(file)) { while(scanner.hasNextLine()) { fileContents.append(scanner.nextLine() + System.lineSeparator()); } return fileContents.toString(); } }