设为首页 加入收藏

TOP

Java文件定位读取
2014-11-24 03:11:36 来源: 作者: 【 】 浏览:1
Tags:Java 文件 定位 读取

1. 使用RandomAccessFile对象的seek函数来实现
public void seek(long pos) throws IOException
RandomAccessFile randomAccessFile = newRandomAccessFile ("./chanel.txt", "r"); // Set the file position 离文件起始位置10字节处randomAccessFile.seek (10);System.out.println(randomAccessFile.readLine());


其中 pos 代表偏移量,pos = 0, 代表 文件起始位置,pos = 10 表示偏移文件起始位置的10个字节处。注意是字节为单位。一个ASCII 码的代表一个字节,如'A' , 'a'。汉字代表两个字节。


以下图片是EditPlus,指示的,我理解一个字节占一个col 。






2. 使用FileChannel的position方法来实现
public abstract FileChannel position(long newPosition) throws IOException
其中newPosition与上面的pos含义一样。
在使用FileChannel之前,必须先打开它。但是,我们无法直接打开一个FileChannel,
需要通过使用一个InputStream、OutputStream或RandomAccessFile来
获取一个FileChannel实例。下面是通过RandomAccessFile打开FileChannel的示例
RandomAccessFile randomAccessFile = newRandomAccessFile ("./chanel.txt", "r"); FileChannel fileChannel = randomAccessFile.getChannel( );//Set the file position离文件起始位置10字节处 fileChannel.position (10);System.out.println(randomAccessFile.readLine());


推荐阅读


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Java使用dom4j解析XML字符串 下一篇关于String拆分和Date类型的转换

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·C++ 语言社区-CSDN社 (2025-12-24 17:48:24)
·CSDN问答专区社区-CS (2025-12-24 17:48:22)
·C++中`a = b = c`与` (2025-12-24 17:48:19)
·C语言结构体怎么直接 (2025-12-24 17:19:44)
·为什么指针作为c语言 (2025-12-24 17:19:41)