Вопрос-ответ

How do I create a Java string from the contents of a file?

Как мне создать строку Java из содержимого файла?

Я уже некоторое время использую приведенную ниже идиому. И, похоже, она наиболее распространена, по крайней мере, на сайтах, которые я посетил.

Есть ли лучший / другой способ преобразовать файл в строку в Java?

private String readFile(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");

try {
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}

return stringBuilder.toString();
} finally {
reader.close();
}
}
Переведено автоматически
Ответ 1

Прочитать весь текст из файла

В Java 11 добавлен метод ReadString() для чтения небольших файлов как String с сохранением символов, завершающих строки:

String content = Files.readString(path, encoding);

Для версий между Java 7 и 11 вот компактная, надежная идиома, заключенная в служебный метод:

static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}

Чтение строк текста из файла

В Java 7 добавлен удобный метод для чтения файла в виде строк текста, представленных в виде List<String>. Этот подход является "с потерями", потому что разделители строк удаляются с конца каждой строки.

List<String> lines = Files.readAllLines(Paths.get(path), encoding);

В Java 8 добавлен Files.lines() метод для создания Stream<String>. Опять же, этот метод с потерями, потому что разделители строк удалены. Если при чтении файла возникает an IOException, он упаковывается в an UncheckedIOException, поскольку Stream не принимает лямбды, которые генерируют проверенные исключения.

try (Stream<String> lines = Files.lines(path, encoding)) {
lines.forEach(System.out::println);
}

Для этого Stream действительно нужен close() вызов; это плохо документировано в API, и я подозреваю, что многие люди даже не замечают, что у Stream есть close() метод. Обязательно используйте ARM-блок, как показано.

Если вы работаете с источником, отличным от файла, вы можете использовать lines() метод в BufferedReader вместо этого.

Использование памяти

Если ваш файл достаточно мал по сравнению с доступной памятью, чтение всего файла сразу может работать нормально. Однако, если ваш файл слишком большой, лучшим подходом может быть чтение по одной строке за раз, обработка ее, а затем удаление перед переходом к следующей. Потоковая обработка таким образом может исключить общий размер файла как фактор, влияющий на ваши требования к памяти.

Character encoding

One thing that is missing from the sample in the original post is the character encoding. This encoding generally can't be determined from the file itself, and requires meta-data such as an HTTP header to convey this important information.

The StandardCharsets class defines some constants for the encodings required of all Java runtimes:

String content = readFile("test.txt", StandardCharsets.UTF_8);

The platform default is available from the Charset class itself:

String content = readFile("test.txt", Charset.defaultCharset());

There are some special cases where the platform default is what you want, but they are rare. You should be able justify your choice, because the platform default is not portable. One example where it might be correct is when reading standard input or writing standard output.


Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the "edited" link on this answer.

Ответ 2

If you're willing to use an external library, check out Apache Commons IO (200KB JAR). It contains an org.apache.commons.io.FileUtils.readFileToString() method that allows you to read an entire File into a String with one line of code.

Example:

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);
}
Ответ 3

A very lean solution based on Scanner:

Scanner scanner = new Scanner( new File("poem.txt") );
String text = scanner.useDelimiter("\\A").next();
scanner.close(); // Put this call in a finally block

Or, if you want to set the charset:

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

Or, with a try-with-resources block, which will call scanner.close() for you:

try (Scanner scanner = new Scanner( new File("poem.txt"), "UTF-8" )) {
String text = scanner.useDelimiter("\\A").next();
}

Помните, что Scanner конструктор может выдавать IOException. И не забудьте импортировать java.io и java.util.

Источник: Блог Пэта Нимейера

Ответ 4
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

Java 7

String content = new String(Files.readAllBytes(Paths.get("readMe.txt")), StandardCharsets.UTF_8);

Java 11

String content = Files.readString(Paths.get("readMe.txt"));
java string file