我得到了这个小代码片段,效果很好:
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 1.7
之前不可用的java.nio包。
现在我需要一种可靠的方法来完成与以前的Java版本相同的操作。
你有好主意吗 ?我唯一能想到的是,用BufferedReader
逐行读取文件,如果读取完成,则以某种方式从中检索最后一个字符。
答案 0 :(得分:3)
(2015年仍在使用Java 6?Ahwell)
这是一个解决方案;请注意,假设您已在文件上打开BufferedReader
:
String line, lastLine = null;
while ((line = reader.readLine()) != null)
lastLine = line;
// obtain the last character from lastLine, as you already do
请注意,这将真实地返回最后一个(java) char ,这可能不是最后一个代码点。
答案 1 :(得分:1)
您可以使用java.io.RandomAccessFile
类:
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;
}
答案 2 :(得分:0)
其中一种方法是
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];
}