简体   繁体   中英

How to skip an input line in Java

I was wonder if there is a method in java that is similar to the.ignore() method from c++, which basically skips 1 line of text in a file. If there isn't one is there anyway I could skip the first line of text in a csv file?

If you are using a file scanner just run nextLine() once and don't store the value.

Scanner myReader = new Scanner(inputFile);
myReader.nextLine();

Assuming you know how to set up a scanner, and new Scanner( new File( name.csv ) ) and all that, I would just use scanner.nextLine(); to consume the first line off of it. You can store it as a string or just get rid of it.

Here is a way to do it with streams:

var path = Path.of("some.txt");
List<String> lines = Files.readAllLines(path)
   .stream()
   .skip(1) //define number of lines to skip
   .collect(Collectors.toList());

To skip at characters level you could still do it with streams or use the skip method from BufferedInputStream:

try (var reader = new BufferedInputStream(new FileInputStream("some.txt")){
    reader.skip(2);
    System.out.println((char) reader.read());
    System.out.println((char) reader.read());
} catch (IOException e) {
    e.printStackTrace();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM