简体   繁体   中英

Is there a way to check if Java has started reading a new line in a text file when reading in a text file

I'm creating a program which reads in large chunks of data and i will need to separate them and i wanted to know if there is a function in java which would notify me when Java starts reading in a new line, by the way I am using scanners to read in my text files, these files are also CSV files if that changes anything.

I've tried looking online for any way of solving this and also read some of the functions of what a scanner can do and couldn't find anything useful

public class ScannerReading {

public static void main(String[] args) throws FileNotFoundException {

    File file = new File("C:\\myfile.txt");
    Scanner scanner = new Scanner(file);
    scanner.useDelimiter(",");
    String data = scanner.nextLine();
    data = scanner.nextLine();

    while(scanner.hasNext()){
        if(data.contains("  ")) {
            System.out.println("I have a line lol");
            }
        System.out.print(data+" ");
        }
    scanner.close();
    }

}

I am expecting an output of Line 1: INFORMATION EXTRACTED FROM THE FIRST LINE

The direct answer to your question is that there is no way to find out if you have just started a new line when you use Scanner::next / Scanner::hasNext . And more generally, there is no way to find out what the last delimiter was. The delimiters are discarded.

As JB Nizet says there are lots of existing open source CSV reader libraries, so there is no need to implement this functionality using Scanner . Indeed, implementing CSV reading properly is not trivial, especially if you need to implement headers, quoting, escaping and/or continuation lines. Using an existing library is advisable.

But if (against advice!) you decide to implement the reader directly, then a more robust approach is to use a nested loop:

  • The outer loop reads complete lines using nextLine
  • The inner loop creates a Scanner for each line to split it into fields.

Except that that doesn't deal with quoting, escaping, continuation lines, etc. The real problem is that the CSV grammar doesn't have a simple context independent delimiter.

I guess I could maybe use some sort of counter to count [fields]

Yea ... but if some of the lines in your CSV are missing fields (eg due to a human error) then counting the fields won't detect this.

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