Ignore the first line of a file

Asked

Viewed 724 times

-2

I would like to know how to ignore a line in a file .csv, because the first line is a kind of title.

try (BufferedReader br = new BufferedReader(new FileReader("C:\\temp\\apartamentos.csv"))) {
        String line = br.readLine();

        while (line != null) {
            String[] files = line.split(",");

            int numero = Integer.parseInt(files[0]);
            double valor =  Double.parseDouble(files[1]);
            apartamentos.add(new Apartamento(numero, valor));

            System.out.println(line);

            line = br.readLine();
        }

3 answers

2

You can even record all the lines in the file in an array, as said in this answer. But remember that in this case the array will have all the contents of the file loaded in memory. In the case of very large files, this can even cause a OutOfMemoryError (for small files, it makes no difference).

If you want to process line by line, without having to load the whole file in memory, you can use this:

try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\temp\\apartamentos.csv"), StandardCharsets.ISO_8859_1))) {
    br.readLine(); // lê a primeira linha e não faz nada com ela

    // lê o restante das linhas
    String line;
    while ((line = br.readLine()) != null) {
        // faz o que precisar com a linha
        System.out.println(line);
    }
}

I used the syntax of Try-with-Resources (available from Java 7), which already automatically closes the file. I did not put a block catch correspondent out of laziness to make the example shorter (but always look for handle mistakes the best way).

I also specified a StandardCharsets (the above value is just an example, switch to the encoding the file is in), because if none is specified, encoding will be used default, which may not be the same as the file - and this may lead to unexpected results.

For more information on what an encoding is, I suggest starting around here.

Another alternative is to use a Scanner:

try (Scanner scanner = new Scanner(new FileInputStream("C:\\temp\\apartamentos.csv"), "ISO-8859-1")) {
    scanner.nextLine(); // ignora a primeira linha

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        System.out.println(line);
    }
}

From Java 8, you can use the bundle java.nio, as indicated in the other answer. Just don’t forget to close the file also:

Path path = Paths.get("C:\\temp\\apartamentos.csv");
try (Stream<String> linhas = Files.lines(path, StandardCharsets.ISO_8859_1)) {
    // skip(1) pula a primeira linha
    linhas.skip(1).forEach(linha -> {
        System.out.println(linha);
    });
}

Files.lines does not automatically close the file, but by putting it in a block Try-with-Resources, i guarantee the closure of the same. In general, always try to close the resources you opened (except some special cases).

Another detail is that Files.lines, for default, uses the encoding UTF-8, and if the file is not in this encoding, a MalformedInputException. So I specified one StandardCharsets (the above value is just an example, switch to the encoding in which the file is).

Another alternative to the previous code is to use a Iterator:

Path path = Paths.get("C:\\temp\\apartamentos.csv");
try (Stream<String> linhas = Files.lines(path, StandardCharsets.ISO_8859_1)) {
    Iterator<String> iterator = linhas.iterator();
    iterator.next(); // ignora a primeira linha

    while (iterator.hasNext()) {
        String linha = iterator.next();
        System.out.println(linha);
    }
}

1

In Java 8 you can do so:

Path path = Paths.get("C:\\temp\\apartamentos.csv");
Files.lines(path).skip(1L).forEach(linha->{
   System.out.println(linha);
}); 

In the skip you pass the amount of rows you want to skip.

-6


I believe that if you are playing the lines in an array, right after you record all the lines in the array you can do a shift to remove the first line.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.