读取文本文件的最后一个字符

Read last character of a text file

我得到了这个运行良好的小代码片段:

List<String> lines = Files.readAllLines(
                Paths.get(f.getAbsolutePath()), Charset.defaultCharset());
if (lines.size() > 0) {
            char c = lines.get(lines.size() - 1).charAt(
                    lines.get(lines.size() - 1).length() - 1); 
}

但这使用 java.nio 包,在 Java 1.7 之前不可用。

现在我需要一种可靠的方法来完成与之前 Java 版本相同的工作。 你有想法吗 ?我唯一能想到的就是用 BufferedReader 逐行读取文件,如果读取完成,以某种方式从中检索最后一个字符。

(2015年还在用Java6吗?嗯嗯)

这是一个解决方案;请注意,假设您已经在文件上打开了 BufferedReader

String line, lastLine = null;
while ((line = reader.readLine()) != null)
    lastLine = line;

// obtain the last character from lastLine, as you already do

请注意,这实际上是 return 最后一个 (java) char,它可能不是最后一个 代码点.

您可以使用 java.io.RandomAccessFile class:

private static byte[] readFromFile(String filePath, int position, int size) throws IOException 
{
    RandomAccessFile file = new RandomAccessFile(filePath, "r");
    file.seek(position);
    byte[] bytes = new byte[size];
    file.read(bytes);
    file.close();
    return bytes;
 }

其中一种方式是这样

    FileReader r = new FileReader("1.txt");
    char[] buf = new char[1024];
    char last = 0;
    for(int n; (n = r.read(buf)) > 0;) {
        last = buf[n - 1];
    }