BufferedReader to skip first line

前端 未结 6 1557
余生分开走
余生分开走 2020-12-24 02:44

I am using the following bufferedreader to read the lines of a file,

BufferedReader reader = new BufferedReader(new FileReader(somepath));
whil         


        
相关标签:
6条回答
  • 2020-12-24 03:05
    File file = new File("path to file");
    FileInputStream fis = new FileInputStream(file);
    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
    String line = null;
    int count = 0;
    while((line = br.readLine()) != null) { // read through file line by line
        if(count != 0) { // count == 0 means the first line
            System.out.println("That's not the first line");
        }
        count++; // count increments as you read lines
    }
    br.close(); // do not forget to close the resources
    
    0 讨论(0)
  • 2020-12-24 03:13

    You can try this

     BufferedReader reader = new BufferedReader(new FileReader(somepath));
     reader.readLine(); // this will read the first line
     String line1=null;
     while ((line1 = reader.readLine()) != null){ //loop will run from 2nd line
            //some code
     }
    
    0 讨论(0)
  • 2020-12-24 03:13

    Use a linenumberreader instead.

    LineNumberReader reader = new LineNumberReader(new InputStreamReader(file.getInputStream()));
                String line1;
                while ((line1 = reader.readLine()) != null) 
                {
                    if(reader.getLineNumber()==1){
                        continue;
                    }
                    System.out.println(line1);
                }
    
    0 讨论(0)
  • 2020-12-24 03:21

    You can use the Stream skip() function, like this:

    BufferedReader reader = new BufferedReader(new FileReader(somepath));   
    Stream<String> lines = reader.lines().skip(1);
    
    lines.forEachOrdered(line -> {
    
    ...
    });
    
    0 讨论(0)
  • 2020-12-24 03:21

    You can do it like this:

    BufferedReader buf = new BufferedReader(new FileReader(fileName));
                String line = null;
                String[] wordsArray;
                boolean skipFirstLine = true;
    
    
    while(true){
                    line = buf.readLine();
                    if ( skipFirstLine){ // skip data header
                        skipFirstLine = false; continue;
                    }
                    if(line == null){  
                        break; 
                    }else{
                        wordsArray = line.split("\t");
    }
    buf.close();
    
    0 讨论(0)
  • 2020-12-24 03:25

    You can create a counter that contains the value of the starting line:

    private final static START_LINE = 1;
    
    BufferedReader reader = new BufferedReader(new FileReader(somepath));
    int counter=START_LINE;
    
    while ((line1 = reader.readLine()) != null) {
      if(counter>START_LINE){
         //your code here
      }
      counter++;
    }
    
    0 讨论(0)
提交回复
热议问题