Adapt txt file reader

0

I was using a manual method to grab a txt file, where the user typed the file name and extension and pressed the button, now they replace it with a code that opens a search box to choose the file in hd.

JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " + selectedFile.getAbsolutePath());
}

And my current code looks like this:

private ArrayList<String> carregaTxt(){
    ArrayList<String> resultado = new ArrayList<String>();

    Scanner ler = new Scanner(System.in);


String nome = nomeTXT.getText();

System.out.printf("\nConteúdo do arquivo texto:\n");
try {

  FileReader arq = new FileReader(nome);
  BufferedReader lerArq = new BufferedReader(arq);

  String linha = lerArq.readLine(); // lê a primeira linha

  while (linha != null) {
    System.out.printf("%s\n", linha);

    String[] palavrasDaLinha = linha.split(" ");

    for(String palavra : palavrasDaLinha) {

        if( palavra.trim().length() > 1 && !"".equals(palavra.trim())) {
            resultado.add(palavra);  
        }

    }

    linha = lerArq.readLine(); // lê da segunda até a última linha
  }

  arq.close();


  System.out.println("\n");
  System.out.printf("Total de palavras no arquivo: %s\n", resultado.size());

} catch (IOException e) {
    System.err.printf("Erro na abertura do arquivo: %s.\n",
      e.getMessage());
}   

    return resultado;  
}
    
asked by anonymous 04.10.2017 / 17:58

1 answer

1

Replace the variable nome with selectedFile . Ex:

File selectedFile = null;

JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION)
    selectedFile = fileChooser.getSelectedFile();

try {
    if (selectedFile != null) {
        FileReader arq = new FileReader(selectedFile);
        BufferedReader lerArq = new BufferedReader(arq);
        //...
    }
} catch (Exception e) {} //tratar exceções...

The class FileReader accepts both% and% objects with the path / filename.

    
04.10.2017 / 18:56