您的位置:首页 > 编程语言 > Java开发

Java读取文件的最后n位

2016-05-04 17:51 656 查看
以读取文件的最后6位为例:

public void readLastLine(String fileString) throws IOException {
File file = new File(fileString);
if (!file.exists() || file.isDirectory() || !file.canRead()) {
return;
}

RandomAccessFile randomFile = null;
try {
System.out.println("随机读取一段文件内容:");
// 打开一个随机访问文件流,按只读方式
randomFile = new RandomAccessFile(file, "r");
// 文件长度,字节数
long start = randomFile.length() - 6;
// 将读文件的开始位置移到beginIndex位置。
randomFile.seek(start);
byte[] bytes = new byte[6];
int byteread = 0;
// 一次读6个字节,如果文件内容不足6个字节,则读剩下的字节。
// 将一次读取的字节数赋给byteread
while ((byteread = randomFile.read(bytes)) != -1) {
for (int i = 0; i < bytes.length; i++) {
Log.d("4345345", "byte" + i + "========="+ bytes[i]);
}

}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: