Reading File in Java

Asked

Viewed 548 times

1

I’m trying to read a file (arquivo.txt) which is in the same folder as my class, but I run the code an error appears that did not find the file. Could someone check what’s wrong? I thank you in advance.

Man arquivo.txt:

Industria;2;90000
Comercio;3;45000
Residencia;1;3000

My Java class:

package jogo;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

public class Tabuleiro {

    private static Scanner scanner;

    public static void main(String[] args) {

        try {
            scanner = new Scanner(new FileReader("arquivo.txt"));
            scanner = scanner.useDelimiter(";");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        while (scanner.hasNext()) {
            String imovel = scanner.next();
            String posicao = scanner.next();
            String valor = scanner.next();
            System.out.println(imovel);
            System.out.println(posicao);
            System.out.println(valor);
        }

    }

}

1 answer

0


Here is a basic and functional example, if you have any problem you can comment below. Don’t forget to pass the correct file path.


try {
        BufferedReader br = new BufferedReader(new FileReader("/root/Documentos/teste.txt"));
        while (br.ready()) {
            String linha = br.readLine();
            System.out.println(linha);
        }
        br.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
  • What about the comma separator? Your code is more of the same as his code, and the delimiter is still missing.

  • I offered a way to read the file and the rest can be handled the way he wants.

  • I managed to resolve, when I saved the file on my pc and step the way I can read.

  • What was the reason for the negative vote in my reply ?

  • It was bad guy, I’ll fix it. I just made the registration on the site. I still do not use direct. rsrsr

  • Thanks for your help.

  • Thanks @Isadoraoliv, anything we will always be here.

  • If in the middle of reading the file occurs a IOException, the method close() will not be called. To fix this, use the Try-with-Resources.

Show 3 more comments

Browser other questions tagged

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