web-dev-qa-db-fra.com

BufferedReader pour ignorer la première ligne

J'utilise la variable bufferedreader suivante pour lire les lignes d'un fichier, 

BufferedReader reader = new BufferedReader(new FileReader(somepath));
while ((line1 = reader.readLine()) != null) 
{
    //some code
}

Maintenant, je veux ignorer la lecture de la première ligne du fichier et je ne souhaite pas utiliser une ligne de compteur int lineno pour conserver le nombre de lignes.

Comment faire ça?

12
Code

Tu peux essayer ça

 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
 }
31

Utilisez un linumberreader à la place.

LineNumberReader reader = new LineNumberReader(new InputStreamReader(file.getInputStream()));
            String line1;
            while ((line1 = reader.readLine()) != null) 
            {
                if(reader.getLineNumber()==1){
                    continue;
                }
                System.out.println(line1);
            }
2
Hirak
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
2
user3743369

Vous pouvez créer un compteur contenant la valeur de la ligne de départ:

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++;
}
1
richersoon

Vous pouvez le faire comme ça:

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
Largo_code