(Java) Error saving multiple lines in a TXT file

Asked

Viewed 83 times

0

I’m trying to record create a log file .txt. I can validate if the file exists using If, but I can’t record outside the if where the file was created. I’m a beginner and believe that the error lies more in logic than the code itself. As the purpose is to create a log file can not lose the already recorded information, you should always add new information in the file.

 String path = "C:\\Users\\Ronison Matos\\Documents\\log.txt";
    File file = new File(path);
long begin = System.currentTimeMillis();

    if(file.exists()){


    }else{

           FileWriter(file));
           System.out.println("Criei novo arquivo em branco para você!");
           FileWriter arq = new FileWriter(file);
    }


    PrintWriter gravarArq = new PrintWriter(arq); // Aqui já dá o erro de acessar no "path"
    gravarArq.write("Caminho da gravação: " + path);
    writer.newLine();
    writer.close();

1 answer

3


The solution to your problem is to simplify the test for existence of the file, because existing or not the file you will use the FileWriter and withdraw the statement FileWriter arq = new FileWriter(file); from within the if.

Create a new file with the function java.io.File.createNewFile() that atomically creates a new empty file if and only if a file with this name does not yet exist.

Solution:

    String path = "C:\\Users\\Ronison Matos\\Documents\\log.txt";
    File file = new File(path);
    long begin = System.currentTimeMillis(); //?????

     // Verifica se o arquivo não existe
     if(!file.exists()){

       // Como o arquivo não existe cria um novo arquivo
       file.createNewFile();

       System.out.println("Criei novo arquivo em branco para você!");
    }

    // Declara arq fora do escopo do if
    FileWriter arq = new FileWriter(file);

    PrintWriter gravarArq = new PrintWriter(arq); 
    gravarArq.write("Caminho da gravação: " + path);
    writer.newLine();
    writer.close();
  • 1

    It worked Augusto for help and explanation! Thank you very much!

Browser other questions tagged

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