I run the program: java Main Tetst.txt The contents of the file is deleted.

import java.io.*; public class Main { public static void main(String args[]){ int i; char string []; FileInputStream fin; FileOutputStream fos; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; String name_file = args[0]; if (args.length!=1){ System.out.println(args[0]); return; } try{ fin = new FileInputStream(name_file); fos = new FileOutputStream(name_file); } catch (FileNotFoundException e){ System.out.println("Невозможно открыть файл"); return; } try{ do{ i = fin.read(); if(i!=-1)System.out.print((char) i); } while (i !=-1); } catch (IOException e){ System.out.println("Ошибка чтения из файла"); } try { do { str = br.readLine(); string = str.toCharArray(); if (!str.equalsIgnoreCase("Exit")) { for (int j = 0; j < str.length(); j++) { fos.write(string[j]); } } } while (!str.equalsIgnoreCase("Exit")); }catch (IOException e){ System.out.println("Ошибка чтения / записи"); } finally { try{ fin.close(); }catch (IOException e){ System.out.println("Ошибка закрытия файла"); } } } } 

    3 answers 3

    You can do something like this:

     //параметр №2 указывает, что данные будут дописыаться в существующий файл //а не будет создаваться новый FileWriter fileWriter = new FileWriter(file, true); PrintWriter printWriter = new PrintWriter(fileWriter); BufferedWriter bufferedWriter = new BufferedWriter(printWriter); bufferedWriter.write("Hello"); 
    • Now it's clear why the file was empty, thanks. - Stupnitsky

    To add content, use the following constructor:

     FileOutputStream(String name, boolean append) 

    with the append parameter true .

    • Yes thank you. This is the solution. - Stupnitsky

    Use this constructor to record to a file.

    FileOutputStream (File file, boolean append)
    File object.

     File file = File("test.txt"); FileOtputStream f = new FileOutputStream(file, true); 
    • Yes, I understand you need to delete comments - Naumov
    • Using this constructor solves the problem. Thank. I correctly understood that if the append parameter is not specified, is the file re-created? - Stupnitsky
    • @MStupnitsky almost, the contents of the file is deleted and a new one is written, overwriting takes place. And the file itself is not deleted;) - Ep1demic