IO Error Exception when trying to manipulate a file

0

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

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, it drops in the Exception IO exception:

    
asked by anonymous 15.10.2016 / 16:31

1 answer

2

If you can not guarantee that the file will always exist, 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 does not exist, just use the createNewFile() method:

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);
}
    
15.10.2016 / 17:13