Adapt txt file reader

Asked

Viewed 52 times

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 that replace by a code that opens a search box to choose the file on the hard drive.

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 is 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;  
}

1 answer

1


Replace the variable nome for 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 Objects File as to String with the file path/name.

  • I did what you recommended, but it does not find selectedFile in Filereader, da as a non-existent variable. I did something wrong?

  • Probably because it’s inside a try-catch. You need to initialize the File out of it. I will include in the reply.

Browser other questions tagged

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