How to set cursor at the beginning of the txt file? [closed]

こ雲淡風輕ζ 提交于 2020-01-07 05:05:14

问题


Same as topic: How to set cursor at the beginning of the txt file in the java? (im using scanner class)


回答1:


I think I interpreted the question wrong first.

I guess you can use RandomAccessFile to do what you wish to do. Here is a simple snapshot of the code that would demonstrate the use of the the RandomAccessFile.

package one;
import java.io.File;
import java.io.RandomAccessFile;
public class one {

    public static void main(String args[])
    {
     try
     {
      RandomAccessFile rac = new RandomAccessFile(new File("/home/.../src/one/a.txt"), "r");
      rac.seek(0);
      System.out.println(rac.readLine());
      System.out.println(rac.readLine());
      //Puts the pointer back to first position 
      rac.seek(0);
      System.out.println(rac.readLine());
     }
     catch(Exception e)
     {
        e.printStackTrace();
     }
    }
}

My a.txt looks like as below:

12345678910
212345678910
312345678910
412345678910
512345678910
612345678910

Hope this helps



来源:https://stackoverflow.com/questions/28953928/how-to-set-cursor-at-the-beginning-of-the-txt-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!