以读取文件的最后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) { } } } }