I need to create a method that will write all the contents entered by the user from the console to the file in the specified path, without overwriting the contents of the file. And writing to the file should be done after entering the wr command on a separate line. I did the method, but as a result of his work, the first cath works right away. When the program shows a debug, the process cannot access the file, as this file is being used by another process.
public static void writeToFileFromConsole(String path){ InputStreamReader reader = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(reader); FileWriter writer = null; BufferedWriter bufferedWriter = null; System.out.println("Enter file content to write in the file:"); try { String command = "wr"; String line; line = br.readLine(); if ((line = br.readLine()).equals(command)) { writer = new FileWriter(path, true); bufferedWriter = new BufferedWriter(writer); bufferedWriter.append("\n"); bufferedWriter.append(line); } }catch (IOException e){ System.err.println("Can't write to file with path " + path); } finally { try { reader.close(); br.close(); if (writer != null){ writer.close(); } if (bufferedWriter != null){ bufferedWriter.close(); } }catch (IOException e){ System.err.println("File with path " + path + " not found" ); } } } What is my mistake? And how to fix that the data entered in the console was recorded in the file.
writeToFileFromConsolein a loop? ............. In general, flows should be closed in the reverse order. at the beginning you need to close thebufferedWriterand then thewriter........... + you can read / write using try with resources - Alexey Shimansky