I have created an object that i then added into an ArrayList. I then saved this arraylist into a .dat file using ObjectOutputStream. I know that the object has been created correctly because the next screen in the program loads directly from the object and the object can be read correctly from the file afterwards. The issue I am running into is that it appears that the object is saving, but it is not willing to be edited. Instead of editing the object in the arraylist, it is creating a new object and saving it again each time.
The code below shows the save function that is performed every time someone finishes the last screen. I am trying to make it so it will check to see if the student exists already in the array, and if so just edit the object. If the student doesn't exist, I want it to take selectedStudent (the object used for all GUI functions) and add it to the array "students" and write the array to the file, overwriting all previous data.
#SuppressWarnings("unchecked")
public static void saveNew() throws ClassNotFoundException, IOException{
int exists = -1;
try{
FileInputStream fis = new FileInputStream("records.dat");
ObjectInputStream in = new ObjectInputStream(fis);
students = (ArrayList<Student>) in.readObject();
in.close();
fis.close();
}
catch(IOException e){
e.printStackTrace();
}
try{
FileOutputStream fos = new FileOutputStream("records.dat", false);
ObjectOutputStream out = new ObjectOutputStream(fos);
for(int i = 0; i<students.size(); i++){
if(students.get(i).getID().equals(selectedStudent.getID())){
exists = i;
}
}
if(exists<0){
students.add(selectedStudent);
}
else{
students.set(i, selectedStudent);
}
out.writeObject(students);
out.close();
}
catch(IOException e){
e.printStackTrace();
}
}
Edit: I noticed that the variable exists was not being used to search for the object which was mistake number one, but I still have the issue where the saved object will not be changed until the method is called a second time. It seems to find it when it is run again, but when it is run the first time it will just create a new student with the edited name.
For example, the first student is created and saved. A second student is the created and saved. When the second student is being edited (without closing the program and restarting) it will, instead of editing the object in the file, create a new student object with the same information directly below the first. If the edit function is run a second time, the second student file is edited correctly but leaves the first as it was.
For a start I would edit these lines
if(students.get(i).getID().equals(selectedStudent.getID())){
exists = i;
}
to
if(students.get(i).getID().equals(selectedStudent.getID())){
System.out.println ("Got it");
exists = i;
break;
}
just to make sure it is working.
Also, you want to change the use of i to exists
else{
students.set(i, selectedStudent); // change to exists
}
I think you must check your variables (if you're reusing any) and initialization code.
The snippet you've posted seems to be fine, so I can't find the error on it.
Here goes a quite similar code that works. I hope it helps.
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class Persistence {
public static void main(String[] args) throws Exception {
File f = new File("records.dat");
// f.delete();
if (!f.exists()){
f.createNewFile();
}
Persistence p = new Persistence();
if (p.peek() == null){
p.init(); //persist an empty list
}
p.saveNew(new Student("ID1","Some Value")); //must insert
p.saveNew(new Student("ID1","Some Other Value")); //must edit
p.saveNew(new Student("ID2","Some Value")); //must insert
ArrayList<Student> list = p.peek();
System.out.println(list);
}
private void save(ArrayList<Student> list) throws Exception{
FileOutputStream fos = new FileOutputStream("records.dat",false);//don't append
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(list);
out.flush();
out.close();
fos.close();
}
private void init() throws Exception{
save(new ArrayList<Student>());
}
private ArrayList<Student> peek() throws Exception{
FileInputStream fis = new FileInputStream("records.dat");
try{
ObjectInputStream in = new ObjectInputStream(fis);
ArrayList<Student> students = (ArrayList<Student>) in.readObject();
return students;
}catch(EOFException eof){
return null;
}finally{
fis.close();
}
}
public void saveNew(Student s) throws Exception {
ArrayList<Student> students = peek();
int editIndex = -1;
for(int i=0;i<students.size();i++){
if (students.get(i).getID().equals(s.getID())){
editIndex = i;
break;
}
}
if (editIndex != -1){
students.set(editIndex, s); //replace
}else{
students.add(s); //add
}
save(students);
}
}
where
import java.io.Serializable;
public class Student implements Serializable{
private static final long serialVersionUID = 1L;
private String ID;
private String s;
public Student(String ID, String s) {
this.ID = ID;
this.s = s;
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
#Override
public String toString() {
return "Student [ID=" + ID + ", s=" + s + "]";
}
}
Related
import java.util.*;
import java.io.*;
class Book implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String author;
public String getAuthor() {
return author;
}
public Book(String name, String author) {
this.name = name;
this.author = author;
}
public void disPlay() {
System.out.print("Book name : " + name);
System.out.println("\tAuthor name : " + author);
}
}
public class Print {
public static void main(String[] args) throws Exception {
writeList();
List<Book> list = readList();
for (Book obj : list)
System.out.println(obj);
}
public static List<Book> readList() throws Exception {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("object.dat"));
#SuppressWarnings("unchecked")
List<Book> readObject = (List<Book>) in.readObject();
in.close();
return readList();
}
public static void writeList() throws Exception {
List<Book> list = new ArrayList<>();
ObjectOutputStream out = null;
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Enter the book, author name : ");
String name = scan.next();
String author = scan.next();
list.add(new Book(name, author));
System.out.print("If you want to save to the list -1, if you don't want, enter 1 : ");
int choice = scan.nextInt();
out = new ObjectOutputStream(new FileOutputStream("object.dat"));
out.flush();
out.close();
System.out.print("Save the list to a file");
}
}
}
I try to get the ArrayList object stored in the file (object.dat), save the Book object in the ArrayList, and then save the ArrayList where the Book object is stored in the file before the end of the program.
The result I want is,
[Results When Program First Runs]
There are no saved values
Enter the book, author name : Harrypotter jkrowling
If you want to save to the list -1, if you don't want, enter 1 : -1
Save the list to a file
and,
[Results on Second and Later]
---Outputs the value stored in the file name---
Book name : Harrypotter
Author name : jkrowling
Enter the book, author name : Twilight StephenieMeyer
If you want to save to the list -1, if you don't want, enter 1 : 1
Save the list to a file
I'd like to print it out like this, but what should I do?
Here is the general way of writing to file in java.
import java.io.FileWriter; // Import the FileWriter class
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Write into file here! ");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
To simplify your code and avoid boilerplates I’d recommend you to look towards specific tools and libs working with files.
There is a good article about loading and reading files using Spring:
Spring Resource
For writing content to a file look towards eg “Apache Commons IO” library provides useful helper methods like:
FileUtils.write(new File(“File.txt"), "Content Text", "UTF-8");
In any case investigate these tools and then think about adopting your requirements in them.
try {
FileWriter writer = new FileWriter("Book.txt");
for(int i = 0 ; i < arraylist.size(); i++){
writer.write(arraylist.get(i).getName();
writer.write(arraylist.get(i).getAuthor();
}
myWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
I use ObjectInput/Output to initialize the hashmap named temp and it put all entry of the hashmap called map that is initialized to new and then use OutputStream to save it in file formatting is .ser
this work perfectly...
import java.io.*;
import java.util.HashMap;
public class PlayerInfo implements Serializable {
ObjectOutputStream out;
ObjectInputStream in;
File userData =new File("path.ser");
HashMap map ;
HashMap temp;
private Integer ID;
String name ;
boolean isItNull =false;
public static void main(String[] args) {
new PlayerInfo();
}
PlayerInfo(){
try {
initializeHashMap();
}catch (Exception e){
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private void initializeHashMap(){
try {
//initialize ObjectInputStream in same method when I use it and close it then
in =new ObjectInputStream(new FileInputStream(userData));
if (isItNull){
temp =new HashMap<Integer,PlayerInfo>();
}else {
map =new HashMap<Integer,PlayerInfo>();
temp = (HashMap<Integer, PlayerInfo>) in.readObject();
in.close();
}
}catch (Exception e){
isItNull =true;
initializeHashMap();
}
}
private void getInfo(){
System.out.println("Ok we are in get info so write your ID:-");
int id = 10;
}
#SuppressWarnings("unchecked")
private void createInfo()throws IOException{
//same here initialize ObjectOutputStreamin same method when I use it and close it then
out =new ObjectOutputStream(new FileOutputStream(userData));
System.out.println("Ok we are in create info so write your ID:-");
ID =10;
String scnS ="Mohammed";
System.out.println("Write your name");
map.put(ID,new PlayerInfo(scnS));
temp.putAll(map);
System.out.println("Saving....");
out.writeObject(temp);
out.close();
}
public PlayerInfo(String name){
this.name =name;
}
}
but this throw EFOException
import java.io.*;
import java.util.HashMap;
public class PlayerInfo implements Serializable {
ObjectOutputStream out;
ObjectInputStream in;
File userData =new File("path.ser");
HashMap map ;
HashMap temp;
private Integer ID;
String name ;
boolean isItNull =false;
public static void main(String[] args) {
new PlayerInfo();
}
PlayerInfo(){
try {
openTheOutPutObjectStreamer();
openTheInPutObjectStreamer();
initializeHashMap();
}catch (Exception e){
e.printStackTrace();
}
}
//here I initialize it in separated method
private void openTheOutPutObjectStreamer()throws IOException{
out =new ObjectOutputStream(new FileOutputStream(userData));
}
//same here I initialize it in separated method
private void openTheInPutObjectStreamer()throws IOException{
in =new ObjectInputStream(new FileInputStream(userData));
}
#SuppressWarnings("unchecked")
private void initializeHashMap(){
try {
if (isItNull){
temp =new HashMap<Integer,PlayerInfo>();
}else {
map =new HashMap<Integer,PlayerInfo>();
temp = (HashMap<Integer, PlayerInfo>) in.readObject();
in.close();
}
}catch (Exception e){
isItNull =true;
initializeHashMap();
}
}
#SuppressWarnings("unchecked")
private void createInfo()throws IOException{
System.out.println("Ok we are in create info so write your ID:-");
ID =10;
String scnS ="Mohammed";
System.out.println("Write your name");
map.put(ID,new PlayerInfo(scnS));
temp.putAll(map);
System.out.println("Saving....");
out.writeObject(temp);
out.close();
}
public PlayerInfo(String name){
this.name =name;
}
}
if you see it the difference is only separate the Object Input/Output to a method and call them
and I am sorry I am a newbie in this website
I don't know a lot about IO but it seems like I cant separate it to methods and call it?
The problem is that in your first code you (correctly) open an input stream uses it and then closes it before doing anything else to the same file but in your second code version you also open the output stream on the same file before having read it and that output stream puts the marker (where to read or write) at the end of the file so when you use your input stream you get an End of file error.
Changing you code to this should work
openTheInPutObjectStreamer();
initializeHashMap();
openTheOutPutObjectStreamer();
This is my first time i try objects serializing.
My problem is that when i call for saving new objects(Reminder.java objects) it saves them in the hash map but when i load it gives me the properties of the last saved object.
So my question is:
1.Saving - How do i "append" objects to a file ?
2.Loading - how to iterate through them and get the right object (using the key class type MyDateClass)
. Example will be welcomed. Thank you.
public void save(MyDateClass chosenDate, String string){
System.out.println("Trying to save");
reminderMap.put(chosenDate, string);
//serializing an object :
this.dateReminder = chosenDate;
this.reminder = string;
try
{
FileOutputStream fileOut =
new FileOutputStream("/tmp/reminder.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/reminder.ser. ");
}catch(IOException i)
{
i.printStackTrace();
}
}
public String Load(MyDateClass chosenDate){
System.out.println("Trying to load");
this.reminder = reminderMap.get(chosenDate);
System.out.println(this.reminder);
// deserialize
Reminder e = null;
try
{
FileInputStream fileIn = new FileInputStream("/tmp/reminder.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Reminder) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
}catch(ClassNotFoundException c)
{
c.printStackTrace();
}
return e.reminder;
}
}
I did a demo and unit test for you, currently I use java.util.Date to substitute your SomeDate class .
update: 2013-12-31
I am not trying to make things complex,but I really feel it is my responsibility to not mislead others,so I try to fixed the code again.Currently, HashMap can't be append,please improve it.Thanks!
this code refactored from your code:
import java.io.*;
import java.util.*;
/**
* refactored by your code
* append object stream haven't realized,please help
* 2013-12-31
*/
public class Reminder implements Serializable {
public static void main(String[] args) {
//do some initialization
Reminder re = new Reminder();
re.put(new Date(System.currentTimeMillis()), "Hope it work!");
re.put(new Date(System.currentTimeMillis()+100), "it work!");
re.put(new Date(System.currentTimeMillis()+200), "Wake up!");
//save to file ,using append mode
String filpath = "/tmp/reminder.ser";
re.save(filpath,true);
//load from file and iterate the key-value pair
Reminder reLoad = Reminder.Load(filpath);
if(reLoad != null) {
Iterator<Map.Entry<Date,String>> it = reLoad.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<Date,String> entry = it.next();
System.out.format("reminder: %tc---%s%n",entry.getKey(),entry.getValue());
}
}
}
public Set<Map.Entry<Date,String>> entrySet() {
return reminderMap.entrySet();
}
public void put(Date chosenDate, String string) {
reminderMap.put(chosenDate, string);
}
public String get(Date chosenDate) {
return reminderMap.get(chosenDate);
}
/**
* serializing an object
* #param filePath path to save file
* #param append indicate whether append or not
*/
public void save(String filePath,boolean append){
System.out.println("Trying to save");
try
{
ObjectOutputStream out = new ObjectOutputStream
( new FileOutputStream(filePath,append));
out.writeObject(this);
out.close();
System.out.printf("Serialized data is saved in "+filePath);
}catch(IOException e)
{
e.printStackTrace();
}
}
/**
* deserialize ,load from file and rebuild object
* #param filePath the path from where to load
* #return a new Object
*/
public static Reminder Load(String filePath) {
System.out.println("Trying to load");
Reminder reminder = null;
try
{
ObjectInputStream in = new ObjectInputStream
(new FileInputStream(filePath));
reminder = (Reminder) in.readObject();
in.close();
}catch(IOException | ClassNotFoundException e)
{
e.printStackTrace();
}
return reminder;
}
private static final long serialVersionUID = 1L;
private Map<Date,String> reminderMap = new HashMap<>();
}
I want to print list of data in file
List<TimeSheetVO> timesheetlist;
java.sql.Date dbdateformat = null;
String date="2013-02-06";
timesheetlist=new ArrayList<TimeSheetVO>();
java.sql.Date dbdate=java.sql.Date.valueOf(date);
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://192.168.1.101:3306/bio_tracker_eden","eden","centris");
String query = "select * from ai_bio_timesheet where ATTENDANCE_DATE=?";
PreparedStatement psmt=con.prepareStatement(query);
psmt.setDate(1,dbdate );
ResultSet rs=psmt.executeQuery();
while(rs.next())
{
timeSheetVO =new TimeSheetVO();
timeSheetVO.setEMP_ID(rs.getString("EMP_ID"));
timeSheetVO.setATTENDANCE_DATE(rs.getString("ATTENDANCE_DATE"));
timeSheetVO.setIN_TIME(rs.getTime("IN_TIME"));
timeSheetVO.setOUT_TIME(rs.getTime("OUT_TIME"));
timesheetlist.add(timeSheetVO);
File file=new File("D:/timesheet.txt");
ObjectOutputStream outstream=new ObjectOutputStream(new FileOutputStream(file));
outstream.writeObject(timesheetlist);
outstream.flush();
outstream.close();
}
}catch (Exception e) {
e.printStackTrace();
}
Here I retrieve the data from database and store the data into list and that list is stored in to file.
But the file is not stored the values.
Can you explain where the problem is?
Here values are coming from database but not displayed in file
I use the below class:
public class TimeSheetVO implements Serializable{
private String EMP_ID;
private String ATTENDANCE_DATE;
private Time IN_TIME;
private Time OUT_TIME;
private Time TOTAL_HOURS;
public String getEMP_ID() {
return EMP_ID;
}
public void setEMP_ID(String eMP_ID) {
EMP_ID = eMP_ID;
}
public String getATTENDANCE_DATE() {
return ATTENDANCE_DATE;
}
public void setATTENDANCE_DATE(String aTTENDANCE_DATE) {
ATTENDANCE_DATE = aTTENDANCE_DATE;
}
public Time getIN_TIME() {
return IN_TIME;
}
public void setIN_TIME(Time iN_TIME) {
IN_TIME = iN_TIME;
}
public Time getOUT_TIME() {
return OUT_TIME;
}
public void setOUT_TIME(Time oUT_TIME) {
OUT_TIME = oUT_TIME;
}
public Time getTOTAL_HOURS() {
return TOTAL_HOURS;
}
public void setTOTAL_HOURS(Time tOTAL_HOURS) {
TOTAL_HOURS = tOTAL_HOURS;
}
#Override
public String toString() {
return new StringBuffer().append(EMP_ID).
append("\n").
append(ATTENDANCE_DATE).
append("\n").
append(IN_TIME).
append("\n").
append(OUT_TIME).toString();
}
}
Here printing the values in file:
[72013-02-0617:50:1519:19:15
, 132013-02-0619:02:1119:02:25
, 212013-02-0618:25:2218:25:22
, 282013-02-0618:25:4318:25:43
, 442013-02-0619:20:2019:41:21
, 562013-02-0617:54:0817:54:08
]
But I want to print like this:
72013-02-0617:50:1519:19:15
132013-02-0619:02:1119:02:25
212013-02-0618:25:2218:25:22
282013-02-0618:25:4318:25:43
442013-02-0619:20:2019:41:21
562013-02-0617:54:0817:54:08
Here am append \n but new line is not coming
Your serialization works fine, I tested locally, you should be able to re create List of TimeSheetVO by doing deserialization.
Primary purpose of java serialization is to write an object into a
stream, so that it can be transported through a network and that
object can be rebuilt again
If you want write the only content of the object in to file, then you would not require serialization, rather write obj.data as plain text in to file.
--- EDIT--
Can you put serialization code outside while loop?
while(rs.next())
{
timeSheetVO =new TimeSheetVO();
timeSheetVO.setEMP_ID(rs.getString("EMP_ID"));
timeSheetVO.setATTENDANCE_DATE(rs.getString("ATTENDANCE_DATE"));
timeSheetVO.setIN_TIME(rs.getTime("IN_TIME"));
timeSheetVO.setOUT_TIME(rs.getTime("OUT_TIME"));
timesheetlist.add(timeSheetVO);
}
File file=new File("D:/timesheet.txt");
ObjectOutputStream outstream=new ObjectOutputStream(new FileOutputStream(file));
outstream.writeObject(timesheetlist);
outstream.flush();
outstream.close();
I am working on an android project that loads data remotely, saves it into an array (if the data is new), writes it to disk as a serializeable, then reads it from disk to load an ArrayList.
Sometimes the ArrayList populates with the data, sometimes it doesn't and the program crashes.
I receive a runtime exception stating: java.land.ClassCastException: java.lang.String cannot be cast to java.io.ObjectStreamClass.
Sometimes I also receive a java.io.StreamCorruptedException, and sometimes I receive and EOFException.
Going through the exception tree, it seems to be originating from this call:
personsArray = (ArrayList<Person>) in.readObject();
Now, sometimes the data loads fine without issues, most of the time the program crashes.
Here is the code that saves the data to disk:
public static boolean saveFromRemoteSource(Context c, ArrayList<?> source){
//Save context
context = c;
//Save source to local file
File file = context.getFileStreamPath(PERSONS_FILE);
//Status if successful in saving
boolean savedStatus = false;
try {
if(!file.exists()){
file.createNewFile();
}else{
//file already exists so don't do anything
}
//now load the data into the file
FileOutputStream fos = context.openFileOutput(PERSONS_FILE, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(source);
oos.close();
savedStatus = true;
} catch(IOException e){
e.printStackTrace();
savedStatus = false;
}
return savedStatus;
}
Here is the code that reads the data from disk:
public static boolean loadPersonsArray(Context c){
context = c;
boolean loadStatus = false;
File file = context.getFileStreamPath(PERSONS_FILE);
try{
if(!file.exists()){
file.createNewFile();
}else {
//File is already created, do nothing
}
BufferedReader br = new BufferedReader(new FileReader(file));
if (br.readLine() != null) {
FileInputStream fis = context.openFileInput(PERSONS_FILE);
ObjectInputStream in = new ObjectInputStream(fis);
personsArray = (ArrayList<Person>) in.readObject();
in.close();
fis.close();
loadStatus = true;
}
br.close();
} catch(IOException e){
e.printStackTrace();
Log.d("TAG", "IOException PERSONS_FILE file: " + e);
loadStatus = false;
} catch (ClassNotFoundException e) {
e.printStackTrace();
Log.d("TAG", "ClassNotFoundException PERSONS_FILE file classnotfound: " + e);
}
return loadStatus;
}
This is the Person class:
import java.io.Serializable;
public class Person implements Serializable, Comparable<Person>{
//Person class
private static final long serialVersionUID = 1L;
private String personID;
private String personName;
private boolean displayPerson;
//default constructor
public Person(){
super();
}
public Person(String personID,
String personName,
boolean displayPerson){
super();
this.personID = personID;
this.personName = personName;
this.displayPerson = displayPerson;
}
//Accessor Methods
public String getPersonID(){
return personID;
}
public String getPersonName(){
return personName;
}
public boolean getDisplayPerson(){
return displayPerson;
}
//setter methods
public void setPersonID(String personID){
this.personID = personID;
}
public void setPersonName(String personName){
this.personName = personName;
}
public void setDisplayPerson(boolean displayPerson){
this.displayPerson = displayPerson;
}
#Override
public String toString(){
return this.getPersonName().replaceAll("[^A-Za-z0-9]", "") + this.getDisplayPerson();
}
public int compareTo(Person otherPerson) {
if(!(otherPerson instanceof Person)){
throw new ClassCastException("Not a valid Person object!");
}
Person tempPerson = (Person)otherPerson;
if(this.getPersonName().compareToIgnoreCase(tempPerson.getPersonName()) > 0){
return 1;
}else if(this.getPersonName().compareToIgnoreCase(tempPerson.getPersonName()) < 0){
return -1;
}else{
return 0;
}
}
}
Where the data comes from to be written to the file
private void downloadPersons(){
HashMap<String, String> params = new HashMap<String, String>();
Kumulos.call("selectAllPersons", params, new ResponseHandler() {
#Override
public void didCompleteWithResult(Object result) {
ArrayList<Object> personsList = new ArrayList<Object>();
for(Object o : (ArrayList<?>)result){
Person person = new Person();
person.setPersonID(replaceNandT((String) ((HashMap<?,?>) o).get("personID")));
person.setLawName(replaceNandT((String) ((HashMap<?,?>) o).get("personName")));
person.setDisplayLaw(stringToBool((String)((HashMap<?,?>) o).get("displayPerson")));
if(person.getDisplayPerson()==true){
personsList.add(person);
}
}
//Save personsList to a file
if(PersonsLoader.saveFromRemoteSource(context, personsList)){
updateVersionNumber();
isFinished=true;
Log.d("TAG", "PersonsLoader.saveFromRemoteSource(context, personsList) success");
}
}
});
}
So what do you think is happening at this call?
Get rid of both the blocks that test File.exists(), and the File.createNewFile() calls.
Opening the file for output will create it if necessary.
When opening the file for reading, if the file doesn't exist a FileNotFoundException will be thrown. There's no point in creating an empty file to avert this: it just leads to other problems.
And get rid of the BufferedReader and readLine() calls too. They serve no useful purpose. There are no lines in an object output stream.