通常我使用扫描器并迭代每一行来获取txt文件的内容:
Scanner sc = new Scanner(new File("file.txt"));
while(sc.hasNextLine()){
String str = sc.nextLine();
}
Java API是否提供一行代码获取内容的方法,例如:
String content = FileUtils.readFileToString(new File("file.txt"))
虽然没有内置的API,但是Guava库提供了这个功能。它是一个非常好用的库。
String content = Files.toString(new File("file.txt"), Charsets.UTF_8);
有类似的方法可以读取任何可读取的内容,或将整个二进制文件加载为字节数组,或将文件读入字符串列表等。
请注意,此方法现已过时。其新的等效方法是:
String content = Files.asCharSource(new File("file.txt"), Charsets.UTF_8).read();
在Java 7中,有一个类似的API。
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public static void main(String[] args) throws IOException {
String content = Files.readString(Paths.get("foo"));
}
Files.readString()
使得读取文件变得更加简单。 - tomFile fileToRead = new File("file.txt");
try( FileReader fileStream = new FileReader( fileToRead );
BufferedReader bufferedReader = new BufferedReader( fileStream ) ) {
String line = null;
while( (line = bufferedReader.readLine()) != null ) {
//do something with line
}
} catch ( FileNotFoundException ex ) {
//exception Handling
} catch ( IOException ex ) {
//exception Handling
}
BufferedReader
和Scanner
都存在问题(前者经常无法检测到新行,后者经常从由org.json库导出的JSON字符串中剥离空格)。虽然还有其他可用的方法,但问题是它们仅在某些Java版本之后受支持(例如对于Android开发人员来说很糟糕),而您可能不想仅仅为了这个目的使用Guava或Apache commons库。因此,我的解决方案是将整个文件读取为字节并将其转换为字符串。下面的代码摘自我的一个业余项目: /**
* Get byte array from an InputStream most efficiently.
* Taken from sun.misc.IOUtils
* @param is InputStream
* @param length Length of the buffer, -1 to read the whole stream
* @param readAll Whether to read the whole stream
* @return Desired byte array
* @throws IOException If maximum capacity exceeded.
*/
public static byte[] readFully(InputStream is, int length, boolean readAll)
throws IOException {
byte[] output = {};
if (length == -1) length = Integer.MAX_VALUE;
int pos = 0;
while (pos < length) {
int bytesToRead;
if (pos >= output.length) {
bytesToRead = Math.min(length - pos, output.length + 1024);
if (output.length < pos + bytesToRead) {
output = Arrays.copyOf(output, pos + bytesToRead);
}
} else {
bytesToRead = output.length - pos;
}
int cc = is.read(output, pos, bytesToRead);
if (cc < 0) {
if (readAll && length != Integer.MAX_VALUE) {
throw new EOFException("Detect premature EOF");
} else {
if (output.length != pos) {
output = Arrays.copyOf(output, pos);
}
break;
}
}
pos += cc;
}
return output;
}
/**
* Read the full content of a file.
* @param file The file to be read
* @param emptyValue Empty value if no content has found
* @return File content as string
*/
@NonNull
public static String getFileContent(@NonNull File file, @NonNull String emptyValue) {
if (file.isDirectory()) return emptyValue;
try {
return new String(readFully(new FileInputStream(file), -1, true), Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
return emptyValue;
}
}
您可以简单地使用getFileContent(file, "")
来读取文件的内容。
建议使用{@code asCharSource(file, charset).read()}。该方法将在2019年1月被删除。
- Stephan