手机版
你好,游客 登录 注册
背景:
阅读新闻

Java文件定位读取

[日期:2013-07-23] 来源:Linux社区  作者:litaoshoujiao [字体:大 中 小]

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核心语法之Java类的基本构成 http://www.linuxidc.com/Linux/2013-06/86408.htm

Java 创建线程池两种不同方法的比较 http://www.linuxidc.com/Linux/2013-06/85366.htm

Java内存模型基本简介 http://www.linuxidc.com/Linux/2013-05/84970.htm

Java注解annotation用法和自定义注解处理器 http://www.linuxidc.com/Linux/2013-05/84969.htm

linux
相关资讯       Java读取文件 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款