Exception java.lang.Numberformatexception (files)

Asked

Viewed 127 times

-2

Guys, by what I checked this code is all correct, including after the String[] linha = arquivo.split(","); if we give a System.out.println(linha[0] + linha[1] + linha[2]) he returns right TV LED 1290.99 1(original file line TV LED, 1290.99, 1), showing that at position 0 = TV LED, position 1 = 1290.99 and position 2 = 1. But at the time of passing the String 1 from position 2 to int he gives this exception... Why ?

        Locale.setDefault(Locale.US);
    Scanner sc = new Scanner(System.in);
    List<Product> list = new ArrayList<>();

    System.out.println("Digite o caminho do arquivo .csv.txt:");
    String caminho = sc.nextLine();

    File file = new File(caminho);
    String acharDiretorio = file.getParent();
    boolean criaSubPasta = new File(acharDiretorio, "\\out").mkdir();
    String criaArquivo = acharDiretorio + "\\out\\summary.csv";

    try(BufferedReader br = new BufferedReader(new FileReader(caminho))){

        String arquivo = br.readLine();

        while(arquivo != null) {
        String[] linha = arquivo.split(",");

        String nome = linha[0];
        double preco = Double.parseDouble(linha[1]);
        int quantidade = Integer.parseInt(linha[2]); //erro aqui, java.lang.NumberFormatException

        list.add(new Product(nome, preco, quantidade));
        arquivo = br.readLine();
        }
        try(BufferedWriter bw = new BufferedWriter(new FileWriter(criaArquivo))){

            for(Product produto : list) {
                bw.write(produto.getNome()+", "+ produto.total());
                bw.newLine();
            }
            System.out.println(criaArquivo + ": SUCESSO");
        }


    }
    catch(IOException e) {
        e.getMessage();
    }
  • Post the exception log, it shows what was found in the variable that could not be parsed.

1 answer

1


It is because there is coming a blank space along with the 1 after the comma, try a

linha[2].trim();

before doing the parse for Integer.

Browser other questions tagged

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