1. Scanning current (as opposed to next) line location. 2. Scanning line X (Java Beginner)

徘徊边缘 提交于 2019-12-11 03:13:51

问题


let's say I have a text file I'm inputing text from...

File file = new File("example.txt");

Scanner inputFile = new Scanner(file);

if I want to reference the next line of text I would do

inputfile.nextLine();
  1. Let's say I want to reference that same line of text again. Is there like a "currentLine()" method? What else could I do?

  2. In general, let's say I want to open the file and refer to the 3rd line of text or the 150th line or whatever, how do I get the Scanner to read that specific line?


回答1:


  1. There is no currentLine() method. You can store current line in the temp var String currLine = inputfile.nextLine(); or you can create your own method.

  2. You can do it this way:


public static void main(String[] args) throws FileNotFoundException{
  Scanner inputFile = new Scanner(new File("example.txt"));
  System.out.println(getLine(150, inputFile));
}
public static String getLine(int line, Scanner input){
  String result = "";
  int lineNr = 1;
  while(input.hasNextLine() && lineNr <= line){
    result = input.nextLine();
    lineNr++;
  }
  return result;
}



回答2:


Scanner is only good if you want to process a file line by line.

You could store each line in a collection for future reference, if you wanted to.

Alternatively you could use Commons IO, e.g. to retrieve a specific line:

List<String> lines = FileUtils.readLines(file);
lines.get(150);

http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html#readLines(java.io.File)

and refer to each line of the line in the manner you suggest. It's hard to suggest anything else until we know what you're trying to do.



来源:https://stackoverflow.com/questions/3983175/1-scanning-current-as-opposed-to-next-line-location-2-scanning-line-x-java

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