IO Exception error when trying to manipulate a file

Asked

Viewed 163 times

0

I have already compiled and run the program in Netbeans and it works normally, but when I run it through the terminal always gives the IO Exception error. Is there any other way to read files without this error?

My function to read file:

public static ArrayList<String> leArquivo(String nomeArq) throws FileNotFoundException, IOException {
        int cont = 1;
        ArrayList<String> frames = new ArrayList<>();
        String linha = "";
        FileReader arq = new FileReader(nomeArq.trim());
        BufferedReader lerArq = new BufferedReader(arq);
        while (linha != null) {
            linha = lerArq.readLine();
            frames.add(cont + "&" + linha + "\n");
            cont++;
        }

        return frames;
    }

function call:

try{
    frame = leArquivo("sw.txt");
}catch (IOException e) {
    Logger.getLogger(ServidorTeste.class.getName()).log(Level.SEVERE, null, ex);
}

Whenever I call the function, falls into the exception of IO Exception:

inserir a descrição da imagem aqui

  • The solution below did not meet you?

  • Yes, you did, thank you!

1 answer

1


If it is not possible to guarantee that the file will always exist, it is interesting to check its existence before manipulating it:

try{

    String path = "sw.txt";

   if(new File(path).exists()) {
        frame = leArquivo(path);
    }
}catch (IOException e) {
    Logger.getLogger(ServidorTeste.class.getName()).log(Level.SEVERE, null, ex);
}

And if you want to create the file when it doesn’t exist, just use the method createNewFile():

try{

    String path = "sw.txt";
    File file = new File(path);

   if(!file.exists()) {
        file.createNewFile();
    }

    frame = leArquivo(path);

}catch (IOException e) {
    Logger.getLogger(ServidorTeste.class.getName()).log(Level.SEVERE, null, ex);
}
  • It worked! I also found that I should exchange my folder files for the way I was running in the terminal

  • @Éowyn yes, you need to enter an absolute path (Type C: path) otherwise outside of netbeans you may not find the file.

Browser other questions tagged

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