0

Using JFileChooser to save file and everything works perfect:

private void saveFileDialog(){

    fileChooser = new JFileChooser(System.getProperty("employees.dat"));
    disableTextField(fileChooser.getComponents());

    fileChooser.setSelectedFile(new File("employees.dat"));
    fileChooser.setDialogTitle("File to save");

    int userSelection = fileChooser.showSaveDialog(this);
    if (userSelection == JFileChooser.APPROVE_OPTION) {
        File fileToSave = fileChooser.getSelectedFile();
        save();
        System.out.println("Save as file: " + fileToSave.getAbsolutePath());
    }
}

Calling method save():

public void save(){
    RandomAccessFile file = null;
    try {
        file = new  RandomAccessFile("employees.dat", "rw");
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     try{
         for(Employee em: list){
      if(list != null){

        file.writeUTF(em.getPps());
        file.writeUTF(em.getName());
        file.writeUTF(em.getSurname());
        file.writeUTF(em.getGender());
        file.writeUTF(em.getDep());
        file.writeInt(em.getSalary());
        file.writeUTF(em.getFullTime());
             }  
         }  

       file.close();

     }catch(IOException e1){
         System.out.println("Cant save");
     }  
}

Opening file on my computer and all data is recorded and saved.

Problem is: I cannot get data from file

Here is my getFromFile method:

   public void getFromFile(){
    RandomAccessFile file = null;
    try {
        file = new  RandomAccessFile("employees.dat", "rw");
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try{
    while ( file.getFilePointer() < file.length() ){ 

          Employee em = new Employee();

                System.out.println("Saving");
                em.setPps(file.readUTF());
                em.setName(file.readUTF());
                em.setSurname(file.readUTF());
                em.setGender(file.readBoolean());
                em.setDep(file.readUTF());
                em.setSalary(file.readInt());
                em.setFulltime(file.readBoolean());  
                list.add( em );

    }
         file.close();
         }catch(IOException e1){
             System.out.println("Cant save");
             e1.printStackTrace();
         }  
}

My JFileChooser for getting from file:

    openItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
        fileChooser = new JFileChooser(".");

        fileChooser.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            System.out.println("Action");

          }
        });

        int status = fileChooser.showOpenDialog(null);

        if (status == JFileChooser.APPROVE_OPTION) {

          File selectedFile = fileChooser.getSelectedFile();
          getFromFile();

          System.out.println(selectedFile.getParent());
          System.out.println(selectedFile.getName());
        } else if (status == JFileChooser.CANCEL_OPTION) {
          System.out.println("calceled");

        }

      }
});

Console shows me System.out.println("Saving");, and then System.out.println("Cant save"); . Seems to me that everything should work, however file is empty and nothing new appear in my program.

Here is following exception coming:

 java.io.EOFException
        at java.io.RandomAccessFile.readFully(RandomAccessFile.java:399)
        at java.io.DataInputStream.readUTF(DataInputStream.java:592)
        at java.io.RandomAccessFile.readUTF(RandomAccessFile.java:921)
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Alex
  • 57
  • 1
  • 7

1 Answers1

1

Your "core" problem is likely here...

System.out.println("Saving");
em.setPps(file.readUTF());
em.setPps(file.readUTF());
em.setName(file.readUTF());
em.setSurname(file.readUTF());
em.setGender(file.readBoolean());
em.setDep(file.readUTF());
em.setSalary(file.readInt());
em.setFulltime(file.readBoolean()); 

You're calling setPps twice.

Also, there is no collation between what you select using the JFileChooser and where the file is getting written to/read from

If we take a quick look at the read/write operations we can see the doubl read operation

+----------------------------------+-------------------------------------+
| Write                            | Read                                |
+----------------------------------+-------------------------------------+
| file.writeUTF(em.getPps());      | em.setPps(file.readUTF());          |
+----------------------------------+-------------------------------------+
| file.writeUTF(em.getName());     | em.setPps(file.readUTF());          |
+----------------------------------+-------------------------------------+
| file.writeUTF(em.getSurname());  | em.setName(file.readUTF());         |
+----------------------------------+-------------------------------------+
| file.writeUTF(em.getGender());   | em.setSurname(file.readUTF());      |
+----------------------------------+-------------------------------------+
| file.writeUTF(em.getDep());      | em.setGender(file.readBoolean());   |
+----------------------------------+-------------------------------------+
| file.writeInt(em.getSalary());   | em.setDep(file.readUTF());          |
+----------------------------------+-------------------------------------+
| file.writeUTF(em.getFullTime()); | em.setSalary(file.readInt());       |
+----------------------------------+-------------------------------------+
|                                  | em.setFulltime(file.readBoolean()); |
+----------------------------------+-------------------------------------+

There's also a disparity between what you're writing and what you're reading

For example, you write the gender using file.writeUTF(em.getGender());, but you read it using em.setGender(file.readBoolean());

You should probably be using file.writeBoolean(em.getGender());

If it saving to the file properly via my JFileChooser, does it mean that there is collation between them?

Let's take a look at your saveFileDialog method

private void saveFileDialog(){

    fileChooser = new JFileChooser(System.getProperty("employees.dat"));
    disableTextField(fileChooser.getComponents());

    fileChooser.setSelectedFile(new File("employees.dat"));
    fileChooser.setDialogTitle("File to save");

    int userSelection = fileChooser.showSaveDialog(this);
    if (userSelection == JFileChooser.APPROVE_OPTION) {
        File fileToSave = fileChooser.getSelectedFile();
        save();
        System.out.println("Save as file: " + fileToSave.getAbsolutePath());
    }
}

You create a local variable called fileToSave which holds (I presume the directory you want the file saved in), but it only has context to this method, no one else can use

So, your method should read...

private void saveFileDialog(){
    save();
}

and it would basically achieve the same result

I'd also consider using something like JAXB which would probably make your life a lot easier

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thank you, I got rid of calling steps twice, but still the same problem. If it saving to the file properly via my JFileChooser, does it mean that there is collation between them? – Alex Apr 10 '16 at 09:05
  • But "how" does the `save` method know where to save the file? You never pass that information to the method – MadProgrammer Apr 10 '16 at 09:07
  • I just go where I want to save my file, and save manually it in my folder for this application. And the open the file there and all data is saved. – Alex Apr 10 '16 at 09:10
  • Since you're completely ignoring the results from the `JFileChooser` why have it anyway? It's just causing confusion in your code – MadProgrammer Apr 10 '16 at 09:13
  • For this moment I am calling setPps only one time. And I am not sure, but why I have boolean and string together when reading and writing gender, because in my Employee class I have the following: `public String getGender() { return gender ? "Male":"Female"; } public void setGender(boolean gender) { this.gender = gender; } ` – Alex Apr 10 '16 at 09:19
  • @Alex Well, that's not confusing at all, the fact is, you've written a `String` but are trying to read a boolean ... how do you think that's going to end? – MadProgrammer Apr 10 '16 at 09:21
  • Sorry about misunderstanding about JFileChooser, but I thought that I need to just put JFileChooser without any directories declared and then just go by myself where I want to save my file. or the is another problem of it? – Alex Apr 10 '16 at 09:22
  • But the program cant allow me to write the `file.writeBoolean(em.getGender());`, because of this line `public String getGender() { return gender ? "Male":"Female"; }` Should then I change this methods in the Employee class? – Alex Apr 10 '16 at 09:24
  • @Alex It would be more consistent – MadProgrammer Apr 10 '16 at 09:25
  • Thank you, I will try to improve everything a little bit later and then let you know. You help is very appreciated. – Alex Apr 10 '16 at 09:27
  • I am not sure is it convenient or not, but it what I did: `public String getGender() { return gender ? "Male":"Female"; } public void setGender(String str) { this.gender = str != null; }` – Alex Apr 10 '16 at 10:49
  • Now it is opening, but every one record is showing twice. I just wonder can I convert in some another way `public void setGender(boolean gender)`, that I could write `readUTF` – Alex Apr 10 '16 at 10:51
  • It's a bit hard to tell, but between write and read, you don't seem to be removing any pre-existing records from the `List`. – MadProgrammer Apr 10 '16 at 11:03
  • okey, how can I do it? do I need to create separate method or it is better to do in reading form file method? – Alex Apr 10 '16 at 11:16
  • Well, when you read the file, I'd either create a new instance of the `list` or simply call `removeAll` on it – MadProgrammer Apr 10 '16 at 11:21