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;
}
I did what you recommended, but it does not find selectedFile in Filereader, da as a non-existent variable. I did something wrong?
– Lucas Silva
Probably because it’s inside a
try-catch
. You need to initialize theFile
out of it. I will include in the reply.– Zulian