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)