I am trying to edit an array of objects after reading them by using Serializable.
The code works fine for new instance of my object but gives a NullPointer exception when I try to edit the object read from file.
public class ShoppingCenter implements Serializable{
// I cant write to file without transient
transient Scanner scan=new Scanner (System.in);
private static final long serialVersionUID = 6529685098267757692L;
//This is the edit details method which will be used to modify the details
public void editDetails()
{
System.out.println("The details are as follows:");
System.out.println("*Name is "+ name);
System.out.println("\t(1-Edit 2-Continue)");
// *******This is where it gives the exception********
if (scan.nextInt()==1)
{System.out.println("\t Write the new value..");
name=scan.next();
System.out.println("Done..");}
System.out.println("*Location is "+ location);
System.out.println("\t(1-Edit 2-Continue)");
if (scan.nextInt()==1)
{System.out.println("\t Write the new value..");
location=scan.next();
System.out.println("Done..");}
}
This is the stack Trace.
java.lang.NullPointerException
at ShoppingCenter.editDetails(ShoppingCenter.java:40)
at Part3Main.searchObject(Part3Main.java:99)
at Part3Main.init(Part3Main.java:130)
at Part3Main.main(Part3Main.java:189)
Here is my driver.
public void init(){
readFile("shoppingCenter");
}
public void readFile(String name){
try{
FileInputStream fis = new FileInputStream(name);
ObjectInputStream ois = new ObjectInputStream(fis);
sc = (ShoppingCenter[]) ois.readObject();
ois.close();
System.out.println("The Object was succesfully read from the file");
//System.out.println(sc[1].toString());
//System.out.println(sc.toString());
}
catch (Exception ex){
ex.printStackTrace();
}
}
A little help would be really appreciated.. Thanks ..
Related
I've reasearched a lot of websites and I couldn't find answear. I'm trying to write to .txt file my ArrayList which constains class objects. Every time I try to do it I`m getting exception. With reading is the same problem. Here is my code:
public static void write()
{
try
{
FileOutputStream out = new FileOutputStream("clients.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);
oout.writeObject(lista);
oout.close();
}
catch(Exception ioe)
{
System.out.println("writing Error!");
welcome();
}
}
public static void read()
{
try
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("clients.txt"));
lista = (List<Client>) ois.readObject();
}
catch (ClassNotFoundException ex)
{
System.out.println("Koniec pliku");
}
catch(IOException ioe)
{
System.out.println("Error!");
welcome();
}
}
I guess you're looking for the Serializable interface of Java. In order to save objects you're class have to implement it.
The question is: What execatly do you want to save? The content of the list so that you can save it in a file and load it afterwards?
This simple example works for me (for the scenario I mention above):
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public User(String name, int ag) {
this.name = name;
this.age = age;
}
#Override
public String toString() {
return (this.name + ' ' + this.age);
}
}
public class Main {
private static List<User> l;
public static void main(String[] args) {
l = new ArrayList<User>();
user1 = new User("John", 22);
user2 = new User("Jo", 33);
l.add(user1);
l.add(user2);
write();
}
public static void write() {
try {
FileOutputStream fos = new FileOutputStream("testout.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(l);
oos.close();
} catch (Exception ioe) {
System.out.println("writing Error!");
}
}
}
Ok I have changed a bit (not each function just the read and write functionality) and this work.
Link to Code.
One important thing is that the Scanner class is not serializable. Therefore, you have to make it static for example.
I am writing a program which requires the opening of a file, adding to it, and then closing it. For some reason when I try to do so, I get a nullPointerException.
Here is what I have in the main class:
public static filer f = new filer();
and then:
f.addStuff("hi");
f.closeFile();
now here is what I have in the file class, which is where I think the problem is right now:
public class filer {
private static Formatter f;//to add to file
private static Scanner s; //to read file
public static File file;
private static boolean ftf = false;
public static void openFile() {
try{ //exception handling
file = new File("jibberish.txt");
//shows if file created
System.out.println("File created: "+ ftf);
// deletes file from the system
file.delete();
// delete() is invoked
System.out.println("delete() method is invoked");
// tries to create new file in the system
ftf = file.createNewFile();
// print
System.out.println("File created: "+ ftf);
Formatter f = new Formatter(file);
Scanner s = new Scanner(file);
FileReader r = new FileReader(file);
/*
f = new Formatter("jibberish.txt"); //will automatically create jibberish.txt if no exist
s = new Scanner("jibberish.txt");
*/ //don't us these because scanner will take type string, easier to clear all other way
}
catch(IOException ioe){
System.out.println("Trouble reading from the file: " + ioe.getMessage());
}
}
public static void addStuff(String toAdd){
f.format("%s ", toAdd);
System.out.printf("%s added", toAdd);
}
public static void closeFile(){ //need to do this to avoid errors
f.close();
s.close();
}
the rest of the class works, i have all the proper imports and stuff
oh and of course here is what comes out of the console:
File created: false
delete() method is invoked
File created: true
Exception in thread "main" java.lang.NullPointerException
at filer.addStuff(filer.java:48)
at transMain.main(transMain.java:40)
You get a NullPointerException because when you call the addStuff method, f has not been initialized and is therefore null. Calling a method on a reference to a null object will result in a NullPointerException.
The problem is with the following line in openFile. You are creating a new local variable called f which hides the field named f declared at class level :
Formatter f = new Formatter(file);
Change the above line as follows so that the class level field f is the one that is initialized in openFile:
f = new Formatter(file);
I am having trouble deserializing an object from a file in Java in a new session.
I can serialize an arraylist to file, and then deserialize it in the same session, however, if I create a new Main object and try to deserialize the same file that worked in the previous session, the code does not work.
Why would this be?
Here is my code:
public void LoadPersonListFromFile(String Filename)
{
try
{
PersonList = new ArrayList<Person>();
ObjectInputStream in = new ObjectInputStream(new FileInputStream(Filename));
ArrayList<Person> PersonList = (ArrayList<Person>) in.readObject();
in.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void SavePersonFileToFile(String Filename)
{
try
{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(Filename));
out.writeObject(PersonList);
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
EDIT
The DeSerialization seems to be working, because if I do a .size() call on the List in the LoadPersonListFromFile method, I get the value of 2. However, if I call the .size() method on the List outside of the LoadPersonListFromFile method, the .size() is shown as 0. Why would this be? Do I need to copy the deserialized ArrayList into the private field?
I have the following private field to store the ArrayList at the top of the class:
private ArrayList<Person> PersonList;
EDIT2
Got it working. Here is the code:
public void LoadPersonListFromFile(String Filename)
{
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream(Filename));
ArrayList<Person> PersonListFromFile = (ArrayList<Person>) in.readObject();
in.close();
PersonList = PersonListFromFile;
}
catch (Exception e)
{
e.printStackTrace();
}
}
It seems that you didn't define a static final long serialVersionUID in Person class. Basically, when you compile a Serializable class that has no serialVersionUID defined in the source code, the Java compiler will define it for you with random value.
To solve the issue, define the following in Person class:
private static final long serialVersionUID = 1L;
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Hi guys i just implemented object files into my program and i am constantly getting the errors (error reading file and problem writing to file) these are 2 errors in my try catch block, when i try to read the file it does not load, saving doesn't work either.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class Stores implements Serializable
{
public static ArrayList<Student> stud1 = new ArrayList<Student>();
public static ArrayList<SubjectTeacher> sTeach1 = new ArrayList<SubjectTeacher>();
private static int iT = 0;
private static int iS = 0;
public static void savet (ArrayList<SubjectTeacher> teachIn, int count)
{
iT = count;
sTeach1 = teachIn;
saveTeachToFile();
}
public static void saves (ArrayList<Student> studIn, int count)
{
iS = count;
stud1 = studIn;
saveStudToFile();
}
public static ArrayList<Student> getStud ()
{
return stud1;
}
public static ArrayList<SubjectTeacher> getTeach ()
{
return sTeach1;
}
public static int getStudSize()
{
return stud1.size();
}
public static int getTeachSize()
{
return sTeach1.size();
}
private static void saveStudToFile()
{
try
{
// create a FileOutputStream object which will handles the writing of the sudent list of objects to the file.
FileOutputStream studentFile = new FileOutputStream("Students.obf");
// the OutputObjectStream object will allow us to write whole objects to and from files
ObjectOutputStream studentStream = new ObjectOutputStream(studentFile);
for(Student item: stud1) // enhanced for loop
// Loop through the list of studentsListIn and for each of these objects, wite them to the file
{
studentStream.writeObject(item);
}
//close the file so that it is no longer accessible to the program
studentStream.close();
}
catch(IOException e)
{
System.out.println("There was a problem writing the File");
}
}
private static void saveTeachToFile()
{
try
{
FileOutputStream teacherFile = new FileOutputStream("Teacher.obf");
ObjectOutputStream teacherStream = new ObjectOutputStream(teacherFile);
for(SubjectTeacher item1: sTeach1) // enhanced for loop
{
teacherStream.writeObject(item1);
}
//close the file so that it is no longer accessible to the program
teacherStream.close();
}
catch(IOException e)
{
System.out.println("There was a problem writing the File");
}
}
public static void loadStudentList()
{
boolean endOfFile = false;
Student tempStudent;
try
{
// create a FileInputStream object, studentFile
FileInputStream studentFile = new FileInputStream("Students.obf");
// create am ObjectImnputStream object to wrap around studentStream
ObjectInputStream studentStream = new ObjectInputStream(studentFile) ;
// read the first (whole) object with the readObject method
tempStudent = (Student) studentStream.readObject();
while (endOfFile != true)
{
try
{
stud1.add(tempStudent);
// read the next (whole) object
tempStudent = (Student) studentStream.readObject();
}
//use the fact that the readObject throws an EOFException to check whether the end of eth file has been reached
catch(EOFException e)
{
endOfFile = true;
}
studentStream.close();
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
catch(ClassNotFoundException e) // thrown by readObject
/* which indicates that the object just read does not correspond to any class
known to the program */
{
System.out.println("Trying to read an object of an unkonown class");
}
catch(StreamCorruptedException e) //thrown by constructor
// which indicates that the input stream given to it was not produced by an ObjectOutputStream object {
{
System.out.println("Unreadable File Format");
}
catch(IOException e)
{
System.out.println("There was a problem reading the file");
}
}
public static void loadTeacherList()
{
boolean endOfFile = false;
SubjectTeacher tempTeacher;
try
{
FileInputStream teacherFile = new FileInputStream("Teacher.obf");
ObjectInputStream teacherStream = new ObjectInputStream(teacherFile) ;
tempTeacher = (SubjectTeacher) teacherStream.readObject();
while (endOfFile != true)
{
try
{
sTeach1.add(tempTeacher);
// read the next (whole) object
tempTeacher = (SubjectTeacher) teacherStream.readObject();
}
//use the fact that the readObject throws an EOFException to check whether the end of eth file has been reached
catch(EOFException e)
{
endOfFile = true;
}
teacherStream.close();
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
catch(ClassNotFoundException e) // thrown by readObject
/* which indicates that the object just read does not correspond to any class
known to the program */
{
System.out.println("Trying to read an object of an unkonown class");
}
catch(StreamCorruptedException e) //thrown by constructor
// which indicates that the input stream given to it was not produced by an ObjectOutputStream object {
{
System.out.println("Unreadable File Format");
}
catch(IOException e)
{
System.out.println("There was a problem reading the file");
}
}
}
Well, for one thing, you should edit the question with the correct code so it doesn't get closed. Second, A couple of things could be happening.
The classes you're writing to file aren't serializable
The files are readonly or write protected somehow
Based on the code from your updated question, it looks like you may be confusing which classes need to implement Serializable. The classes that need to implement that are the ones you're actually writing to file (ie SubjectTeacher, etc.).
Check those two, and let me know what you find.
Also, I'd suggest stepping the code and seeing what the exceptions look like at runtime. You'll get a much better idea of what's going on.
Alright, so I am writing a Java application to import a csv file and then loop through the results, and load them into an array. I am importing the file correctly because it doesn't through an Exception. My issues is that when I try to count the number of records in the FileInputStream I am trapped in an infinite loop. What could be the issue here. Heres the code:
This is my class with a Main method which calls go():
public void go() {
pop = new PopularNames();
popGui = new PopularNamesGui();
String file = popGui.userInput("Enter the correct name of a file:");
pop.setInputStream(file);
pop.getNumberOfNames();
}
This is the class PopularNames (pop), and in the below method I am setting the inputStream var to a new FileINputStream. The file name is provided by the user.
public void setInputStream(String aInputStream) {
try {
inputStream = new Scanner(new FileInputStream(aInputStream));
} catch (FileNotFoundException e) {
System.out.println("The file was not found.");
System.exit(0);
}
}
This is the trouble method. Where I am simply looping through the FileInputStream and counting the number of records:
public void getNumberOfNames() {
while (this.inputStream.hasNext()) {
fileDataRows++;
}
}
public void getNumberOfNames() {
while (this.inputStream.hasNext()) {
inputStream.nextLine(); // Need to read it so that we can go to next line if any
fileDataRows++;
}
}