0

i have a problem in my java exercise. i need to print a multiply contact information to a file, but when i print more then 1 contact, only 1 contact is displayed in the file.. i tried to debug that but i cant find any mistake i will put the code of my classes here:

This is Demo Class which i run the code from

public class Demo {

public static void main(String[] args) {

    System.out.println("Insert number of Contacts:");
    Scanner scanner = new Scanner(System.in);
    int val = scanner.nextInt();
    Contact[] contacts = new Contact[val];

    for(int i = 0 ; i < val; i++) {
        System.out.println("Contact #"+(i+1));
        System.out.print("Owner: \n");
            String owner = scanner.next();
        System.out.print("Phone number: \n");
            String phoneNum = scanner.next();

        System.out.print("Please Select Group:\n"
                + "1 For FRIENDS,\n" + 
                "2 For FAMILY,\n" + 
                "3 For WORK,\n" + 
                "4 For OTHERS");
        int enumNum = scanner.nextInt();
        Group group;

        switch(enumNum) {       
        case 1:
            group=Group.FRIENDS;
            break;
        case 2:
            group=Group.FAMILY;
            break;
        case 3:
            group=Group.WORK;
            break;
        default:
            group=Group.OTHERS;     
        }//switch end

        contacts[i] = new Contact(owner,phoneNum,group);

    }//loop end
    System.out.println("Insert File name");
    String fileName = scanner.next();
    File f=null;
    for(int i = 0 ; i < val; i++) {
        if(i==0) {
            f = new File(fileName);
            contacts[0].Save(fileName);
        }
        else {

            contacts[i].Save(f);        
        }

    }

}

}

This is Contact Class:

enum Group {
FRIENDS,
FAMILY,
WORK,
OTHERS

}; public class Contact {

private String phoneNumber,owner;
private Group group;
PrintWriter pw = null;


  public Contact(String owner ,String phoneNumber,Group group) {
      setPhoneNumber(phoneNumber);
      setOwner(owner);
      setGroup(group);
  }

  public Contact(String fileName) {
      File file = new File(fileName+".txt");


      try {
        Scanner scanner = new Scanner(file);
         phoneNumber=scanner.nextLine();
         owner=scanner.nextLine();
         String str=scanner.nextLine();
         group = Group.valueOf(str);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
      catch(Exception e) {
          e.printStackTrace();
      }

  }

  public Contact(File file) {

      try {
        Scanner scanner = new Scanner(file);
         phoneNumber=scanner.nextLine();
         owner=scanner.nextLine();
         String str=scanner.nextLine();
         group = Group.valueOf(str);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
      catch(Exception e) {
          e.printStackTrace();
      }

  }

public String getPhoneNumber() {
    return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
}

public String getOwner() {
    return owner;
}

public void setOwner(String owner) {
    this.owner = owner;
}
public Group getGroup() {
    return group;
}
public void setGroup(Group group) {
    this.group = group;
}   
public void Save(String fileName) {

    File f = new File(fileName+".txt");

    try {
        if(f.createNewFile()) {
            System.out.println("File created");
            pw = new PrintWriter(f); //יצירת מדפסת לקובץ    
            pw.println(phoneNumber+"\n"+owner+"\n"+group+"\n\n\n");

        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    pw.close();

}

public void Save(File f) {



    PrintWriter pw=null;
    try {
        pw = new PrintWriter(f);

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    pw.println(phoneNumber+"\n"+owner+"\n"+group);
    pw.close();

}   

public String toString() {
    return phoneNumber+"\n"+owner+"\n"+group;


}

}

3 Answers3

0

From the Javadoc of the constructor of PrintWriter:

public PrintWriter​(File file)
Parameters: file - The file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

In the Save function you create a PrintWriter everytime. So everytime the file is truncated, and then you lose the contact you saved before.

Francesco
  • 897
  • 8
  • 22
  • There is 2 Save methods(One-that gets a String, two- that gets a File), Which one is the wrong one? –  May 16 '20 at 18:10
  • Yes, because from the second contact you call the second `Save` function. Anyway, the constructor with the filename as parameter has the same behaviour. You can check its Javadoce [here](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/io/PrintWriter.html#%3Cinit%3E(java.lang.String)) – Francesco May 16 '20 at 18:13
  • Excuse me for being a little ignorant, i cant seem to find the exact line to remove, can u mark this out for me please? –  May 16 '20 at 18:16
  • There's no line to remove. You have to change the way you use the PrintWriter. Check [this answer](https://stackoverflow.com/questions/8210616/printwriter-append-method-not-appending). – Francesco May 16 '20 at 18:18
0

Every time you create PrintWriter the file is being overwritten. Since you create a new PrintWriter for each contact, the file contains only the last contact information. What you should do is to create PrintWriter only once and use it for all contacts.

Firstly, let's create a new save method with such signature:

public void save(PrintWriter writer)

I have also used the lowercase name of the method due to Java naming convention.

Now the implementation of save method will look like this:

writer.println(phoneNumber);
writer.println(owner);
writer.println(group + "\n\n\n");

Then we should replace the usage of Save method with the new one. Here is your code:

String fileName = scanner.next();
File f = null;
for (int i = 0; i < val; i++) {
    if(i == 0) {
        f = new File(fileName);
        contacts[0].Save(fileName);
    } else {
        contacts[i].Save(f);        
    }
}

In order to fix the issue we can change it like this:

String fileName = scanner.next();
File file = new File(fileName);
try (PrintWriter writer = new PrintWriter(file)) {
    for (int i = 0; i < val; i++) {
        contacts[i].save(writer);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

I have also used try-with-resources which closes the PrintWriter automatically.

Ihor Dobrovolskyi
  • 1,241
  • 9
  • 19
0

Since File I/O classes in java use Decorator Design pattern, you can use a FileWriter to take advantage of appending to a file. So you can use this code for Save() method :

public void Save(String fileName) {

File f = new File(fileName+".txt");

try {

        //System.out.println("File created");  You don't need to create new file.
        FileWriter fw=new FileWriter(f,true):// second argument enables append mode

        pw = new PrintWriter(fw); //יצירת מדפסת לקובץ    
        pw.println(phoneNumber+"\n"+owner+"\n"+group+"\n\n\n");

} catch (IOException e) {
    e.printStackTrace();
}
pw.close();

}
Omid.N
  • 824
  • 9
  • 19