Link to home
Start Free TrialLog in
Avatar of Element_T
Element_TFlag for Germany

asked on

read File and write in to file without erasing

Now I can read the file with a java code, how I can write in to file without erasing anything?

The text which is in the file before have to be untasted.

But my code delete the text which is written before.

Do anyone has an idea how I can read  two files and put it in to one or in to new one?

Thanks.


import java.io.*;
public class LiesDateiEin {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // Dateiname wir übergeben

        String filenameIn = args [0];

        try {

             FileInputStream fis = new FileInputStream (filenameIn);
             InputStreamReader isr = new InputStreamReader(fis);
             BufferedReader bur = new BufferedReader (isr);

             // die erste Zeile wird eingelesen

             String sLine = bur.readLine();

             // lies alle Zeilen aus, bis keine mehr vorhanden sind
             // und gib sie nacheinander aus
             //falls von vornherein nichts in der Datei enthalten
             // ist, wird dieser Prorammabschiniit übersprungen

             int zaehler = 0;

             while (sLine !=null){
                 System.out.println ("Zeile"+zaehler+":"+sLine);
                 sLine = bur.readLine();
                 zaehler++;
             }
             // schliess die Datei
             bur.close();

        }catch (IOException eIO){
            System.out.println ("folgender Fehler trat auf: "+eIO);
        }

        String filenameOutput = args [0];

        try {

            BufferedWriter myWriter = new BufferedWriter(new FileWriter(filenameOutput, false));

            //schreibe zeilenweise in die Datei filename Output

            myWriter.write("Hans Mueller \n");
            myWriter.write("Gundel Gaukel \n");
            myWriter.write("Fred Feuermacher\n");

            myWriter.close();
        }
        catch (IOException eIO){
            System.out.println("Folgender Fehler trag auf:"+ eIO);
        }

    }

}

Open in new window

SOLUTION
Avatar of afibarra
afibarra
Flag of Mexico image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sorry, my mistake about posting your code.

You are using FileWriter which has a FileWriter(File file, boolean append) constructor.

If append = true then bytes will be written to the end of the file rather than the beginning
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You still need to read both files line by line to merge them into one using the same way =)
Why is he closing it?