1

I am trying to Write new content to the file i've created but when i input some new values it deletes my last values and replace it with the new ones, Is there any way to keep putting new values and put that information in new lines of the file?

    String line = "";
    System.out.println( "Escriba el ID" );
    CL.setID( reader.next() );
    System.out.println( "Escriba el Presupuesto" );
    CL.setPresupuesto( reader.next() );
    System.out.println( "Escriba el Nombre del cliente" );
    CL.setNombre( reader.next() );

    try {
        BufferedReader input = new BufferedReader( new FileReader( file ) );
        Scanner input2 = new Scanner( file );
        PrintWriter output = new PrintWriter( file );

        output.println( "ID: #" + CL.getID() );
        output.println( "Presupuesto: " + CL.getPresupuesto() + " $" );
        output.println( "Nombre: " + CL.getNombre() );
        output.println( line );
        output.println( "----------------------------------------" );
        output.close();
    }
    catch( IOException ex ) {
        System.out.println( "Error!!!!" );
    }

    try {
        Scanner input = new Scanner( file );

        String ID = input.nextLine();
        String c = input.nextLine();
        String Name = input.nextLine();
        System.out.printf( "%s \n%s$\n%s\n", ID, c, Name );
        System.out.println( "Cliente Añadido exitosamente!!!" );
        input.close();

    }
    catch( FileNotFoundException ex ) {
        System.out.println( "ERROR!!!!!!!" );
    }
Jabir
  • 2,776
  • 1
  • 22
  • 31

3 Answers3

1

You are using PrintWriter and by default it does not open file in append mode.

You need to open file in append mode:

PrintWriter pw = new PrintWriter(new FileOutputStream( file, true /* append = true /));

Detailed documentation link

Jabir
  • 2,776
  • 1
  • 22
  • 31
0

You can do so by getting all of the lines of a file, adding the lines you want to the end of that list, deleting the old file, then re-writing the new & old lines to the file. This is using Java 8 and makes it way simpler

public static void addLines(String file, String...content) {
    Path path = Paths.get(file);
    List<String> existingContent = Files.readAllLines(path);
    existingContent.addAll(content);
    if (Files.exists(path)) {
        Files.delete(path);
    }
    Files.write(path, existingContent);
}
Joe
  • 1,316
  • 9
  • 17
0

You can just set append-flag on FileOutputStream:

PrintWriter output = new PrintWriter(new FileOutputStream(new File(file), true);
output.append("ID: #" + CL.getID());

Javadoc says:

Parameters:

file - the file to be opened for writing.
append - if true, then bytes will be written to the end of the file rather than the beginning

Seb
  • 1,721
  • 1
  • 17
  • 30