I have encountered a weird behaviour of the ObjectOutputStream / ObjectInputStream.
I want to write a specific amount of Objects of the type Sitzplatz to the file belegung. So far so good. But if I try to read these Objects again they all just return null
Here is my Code:
public void getBelegtePlaetze() {
if (belegung.exists()) {
try {
FileInputStream fis = new FileInputStream(belegung);
ObjectInputStream ois = new ObjectInputStream(fis);
Sitzplatz platz = (Sitzplatz) ois.readObject();
while (platz != null) {
System.out.println(platz.getId());
platz = (Sitzplatz) ois.readObject();
}
ois.close();
fis.close();
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void speichereSitzplatzDaten() {
FileOutputStream fos;
if (!belegung.exists()) {
try {
belegung.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try {
fos = new FileOutputStream(belegung, true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
for (int i = 0; i < kundenListe.size(); i++) {
Sitzplatz platz = kundenListe.get(i).getPlatz();
platz.setId(Integer.toString(i));
oos.writeObject(platz);
}
oos.writeObject(null); // Markiert EOF
oos.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Since I have already worked with me ArrayList kundenListe quite a bit in my program, I can be 100% sure that the data in it is properly set.
I have also already used the ObjectOuputStreamin this program before and nearly copied the code, but still it does not work.
Can you tell me what I'm doing wrong?
UPDATE:
I've tried the suggestions from the comments, but I still have the same issues.
I have reduced the code to the little piece below, which should work 100%, since I have that code already in use in another class. No idea why it works in the other class and not in that one.
private File belegung = new File("belegung.kos");
public void getBelegtePlaetze() {
if (belegung.exists()) {
try {
FileInputStream fis = new FileInputStream(belegung);
ObjectInputStream ois = new ObjectInputStream(fis);
Pakett platz = (Pakett) ois.readObject();
System.out.println(platz.getId());
ois.close();
fis.close();
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void speichereSitzplatzDaten() {
FileOutputStream fos;
if (!belegung.exists()) {
try {
belegung.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
}
try {
fos = new FileOutputStream(belegung);
ObjectOutputStream oos = new ObjectOutputStream(fos);
Pakett platz = new Pakett();
platz.setId("test");
oos.writeObject(platz);
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Related
something is really messed up. I've got a ".ser" document in the assets folder, which stores an ArrayList of Objetcs. In an android application, I want to read this objects. There are a lot of posts related to this issue, however none of them could solve my problem. The strange part is, when I am using similar code in non - android context / "normal" java, it works properly. Here, the last line throws a NullPointerException - What is going wrong?
public void getData() {
ArrayList<MyClass> output= null;
InputStream is = null;
ObjectInputStream ois = null;
try{
is = this.getAssets().open("data.ser");
ois = new ObjectInputStream(is);
output = (ArrayList<MyClass>)ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.d("TAG", output.get(0).getId());
}
I would create a class and place the array within a single object:
public class ListObjects implements Serializable {
List<MyClass> listMyClass = new ArrayList<>();
public ListObjects(){
}
public List<MyClass> getListMyClass() {
return listMyClass;
}
public void setListMyClass(List<MyClass> listMyClass) {
this.listMyClass = listMyClass;
}
}
I had a similar problem. And it was because the name of the package in the java app was not called the same as the package name in android. And therefore I did not recognize them as equal objects. This is how I do it:
public static Object fromData(byte[] data) {
ObjectInputStream ois = null;
Object object = null;
try {
ois = new ObjectInputStream(
new ByteArrayInputStream(data));
object = ois.readObject();
} catch (Exception ex) {
Logger.getLogger(ModeloApp.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
ois.close();
} catch (Exception ex) {
Logger.getLogger(ModeloApp.class.getName()).log(Level.SEVERE, null, ex);
}
}
return object;
}
I need to pass some Bitmaps from one activity to another, and, since the size limit of the Bundle won't let me pass these images (even using a byte array*), I thought that I could use a getter method between these Activities.
-But, since I'm still not a master in Android (Java), I don't know if that would make any difference, and, if it does, what should I watch out for when using it.
the byte array did reduce the total size(at about 60%), but it still wasn't enough
scaling down is a way out, but just in case any other solution works
save your object in a file
private void saveDataToFile() {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = getContext().openFileOutput("fileName", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(fileOutputStream);
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
try {
if (objectOutputStream != null) {
objectOutputStream.writeObject(yourObject); //which data u want to save
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (objectOutputStream != null) {
objectOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Retrieve the object from another activity
private void getDataFromFile() {
FileInputStream fileInputStream = null;
try {
fileInputStream = getContext().openFileInput("fileName");
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(fileInputStream);
} catch (IOException |NullPointerException e) {
e.printStackTrace();
}
try {
yourObject = (ObjectClass) objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Pass through Uri by writing getter method in POJO class
If you want to use getter setter, just create URI of your bitmap and pass to setter method in POJO class and then retrieve using getter method of POJO class.
I want to maintain database of users of a Bank for my project. I am able to save the number of users in one serializable file. But when I try to save the user to database it adds only the latest one to database.
Below is the sneak peak of code which writes the objects:
if(e.getSource()==submit) {
if(uFName != null && uLName != null && uInitialDeposit !=0) {
if(uAccountType=="Savings") {
Random randomGenerator = new Random();
//Gets the number of users from file if file exists
File f = new File(fileNameAdmin);
if(f.exists() && !f.isDirectory()) {
admin=db.readFromAdminDatabase();
}
u[admin.numberOfUsers]= new User();
u[admin.numberOfUsers].fName=uFName;
u[admin.numberOfUsers].lName=uLName;
u[admin.numberOfUsers].initalDeposit=uInitialDeposit;
u[admin.numberOfUsers].interestRate=uInterestRate;
u[admin.numberOfUsers].accountType="Saving";
u[admin.numberOfUsers].accountNumber=690000+admin.numberOfSavingsAccount;
//Generates a 4 digit random number which will be used as ATM pin
u[admin.numberOfUsers].atmPin=randomGenerator.nextInt(9999-1000)+1000;
//A savings account will be created
sa[admin.numberOfSavingsAccount]=new SavingsAccount(u[admin.numberOfUsers].accountNumber,u[admin.numberOfUsers].fName,u[admin.numberOfUsers].lName,
u[admin.numberOfUsers].initalDeposit,
u[admin.numberOfUsers].interestRate);
u[admin.numberOfUsers].sa=sa[admin.numberOfSavingsAccount];
System.out.println(u[admin.numberOfUsers].sa.balance);
JOptionPane.showMessageDialog(submit,"Congratulations! You are now a member of Symbiosis Bank."
+ "\nYour account number is "+u[admin.numberOfUsers].accountNumber
+" and your ATM Pin is "+u[admin.numberOfUsers].atmPin,"Account Created",JOptionPane.INFORMATION_MESSAGE);
try {
//for(int j = 0; j<admin.numberOfUsers; j++)
db.addUserToDatabase(u[admin.numberOfUsers]);
admin.numberOfSavingsAccount++;
admin.numberOfUsers++;
db.updateAdminDatabase(admin);
dispose();
setVisible(false);
//Welcome welcome = new Welcome();
//welcome.setVisible(true);
InitialInput back = new InitialInput();
back.setVisible(true);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
The database class which has functions to write to database:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Database implements Serializable {
String fileName = System.getProperty("user.home")+"/db.ser";
String fileNameAdmin = System.getProperty("user.home")+"/admindb.ser";
public void addUserToDatabase(User u){
FileOutputStream fos;
try {
fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(u);
oos.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
#SuppressWarnings("finally")
public User readFromUserDatabase() {
FileInputStream fis;
User temp = null;
try {
fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
temp = (User)ois.readObject();
//System.out.println(temp.fName);
ois.close();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
return temp;
}
}
public void updateAdminDatabase(Administrator admin) {
FileOutputStream fos;
try {
fos = new FileOutputStream(fileNameAdmin);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(admin);
oos.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
#SuppressWarnings("finally")
public Administrator readFromAdminDatabase() {
FileInputStream fis;
Administrator temp = null;
try {
fis = new FileInputStream(fileNameAdmin);
ObjectInputStream ois = new ObjectInputStream(fis);
temp = (Administrator)ois.readObject();
//System.out.println(temp.fName);
ois.close();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
return temp;
}
}
}
The code which is trying to read the database:
public void actionPerformed(ActionEvent e) {
if(e.getSource()==deposit) {
//Ask the amount to deposit
int userAmountToDeposit;
try {
for(int i = 0; i<=admin.numberOfUsers; i++) {
u[i] = db.readFromUserDatabase();
System.out.println(u[i].accountNumber);
}
for(int j =0; j<=admin.numberOfUsers; j++) {
if(u[j].accountNumber==userAccountNumber) {
if(u[j].atmPin==userPin) {
u[j].accountBalance=u[j].sa.balance;
u[j].sa.deposit(10);
u[j].accountBalance=u[j].sa.balance;
System.out.println(u[j].accountBalance);
}
}
}
}
Inorder to write and read multiple objects please try as below
Writing multiple object into List
WriteObject wo=new WriteObject(20, "Mohan");
WriteObject wo1=new WriteObject(21, "Mohanraj");
ArrayList<WriteObject> woi=new ArrayList<>();
try {
FileOutputStream fop=new FileOutputStream("c://object.ser");
ObjectOutputStream oos=new ObjectOutputStream(fop);
woi.add(wo);
woi.add(wo1);
oos.writeObject(woi);
} catch NotFoundException e) {
}
Reading all objects from file
try {
FileInputStream fis=new FileInputStream("C://object.ser");
ObjectInputStream ois=new ObjectInputStream(fis);
WriteObject wo=null;
WriteObject[] woj=new WriteObject[5];
ArrayList<WriteObject> woi=new ArrayList<>();
woi=(ArrayList<WriteObject>)ois.readObject();
for(int i=0;i<woi.size();i++){
woi.get(i).getvalues();
}
Here getvalues() is method present in Writeobject class. Follow the same mechanism for your code snippet
If you want to fix it rapidly, you can create a list and store first and foremost your objects in the list (may be ArrayList or List), and then you'll save this list on your file. That is the nice method. Make sure that your objects are serializable.
below, listeVoitures is a stactic variable that will contain all
object that i'm going to retrive from file.
public static void saveVehiculeInFile(ArrayList vehiculeList) {
ObjectOutputStream ous = null;
//ArrayList<Vehicule> listVehiculeToSave = new ArrayList<>();
try {
ous = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(new File("garage.txt"))));
try {
ous.writeObject(vehiculeList);
System.out.println("\t=====> Les vehicules *** ont été ajouter dans le garage.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ous != null) {
try {
ous.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This method below is for retrive data from file
public static void readVehiculeFromFile() {
ObjectInputStream ins = null;
ArrayList<Vehicule> v = null;
try {
ins = new ObjectInputStream(new BufferedInputStream(new FileInputStream(new File("PoweredGarage.txt"))));
try {
v = (ArrayList<Vehicule>)ins.readObject();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for (Vehicule vehicule : v) {
listeVoitures.add(vehicule);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (ins != null) {
try {
ins.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I'm having problems with appending a generic object within an existing file. This method is supposed to append the object to the existing file if the parameters are "true" and overwrites the entire file if "false". The "false" statement works perfectly fine, it overwrites the entire file but I can't seem to get the append one to work. It seems to do nothing at first glance but when I placed a simple System.out.println("test"); in the while (true) loop, it runs forever. How can I fix this?
public <T> void writeOneObject(T type, boolean append) throws NotSerializableException{
if (append == true){
//TODO
if (file.exists ()){
ObjectOutputStream ois = null;
try{
ois = new ObjectOutputStream (new FileOutputStream (file, true));
while (true){
ois.writeObject(type);
}
}catch (StreamCorruptedException e){
}catch (EOFException e){
}catch (Exception e){
e.printStackTrace ();
}finally{
try{
if (ois != null) ois.close();
}catch (StreamCorruptedException e){
}catch (IOException e){
e.printStackTrace ();
}
}
}
}
else { //overwrites the entire file
try {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(type);
oos.flush();
oos.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (StreamCorruptedException e) {
System.out.println("error");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I also have this inside the class:
class NoHeaderObjectOutputStream extends ObjectOutputStream {
public NoHeaderObjectOutputStream(OutputStream os) throws IOException {
super(os);
}
protected void writeStreamHeader() {}
}
I have following code :
// Read properties file.
Properties properties = new Properties();
try {
properties.load(new FileInputStream("filename.properties"));
} catch (FileNotFoundException e) {
system.out.println("FileNotFound");
}catch (IOException e) {
system.out.println("IOEXCeption");
}
Is it required to close the FileInputStream? If yes, how do I do that? I am getting a bad practice error in my code checklist . Asking it to put finally block.
You must the close the FileInputStream, as the Properties instance will not. From the Properties.load() javadoc:
The specified stream remains open after this method returns.
Store the FileInputStream in a separate variable, declared outside of the try and add a finally block that closes the FileInputStream if it was opened:
Properties properties = new Properties();
FileInputStream fis = null;
try {
fis = new FileInputStream("filename.properties");
properties.load(fis);
} catch (FileNotFoundException e) {
system.out.println("FileNotFound");
} catch (IOException e) {
system.out.println("IOEXCeption");
} finally {
if (null != fis)
{
try
{
fis.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Use try-with-resources since Java 7:
final Properties properties = new Properties();
try (final FileInputStream fis =
new FileInputStream("filename.properties"))
{
properties.load(fis);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound: " + e.getMessage());
} catch (IOException e) {
System.out.println("IOEXCeption: " + e.getMessage());
}
You should always close your streams, and doing it in the finally block is a good practice. The reason for this is that the finally block always gets executed, and you want to make sure that the stream is always closed, even if Something Bad happens.
FileInputStream inStream = null;
try {
inStream = new FileInputStream("filename.properties");
properties.load(inStream);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound");
} catch (IOException e) {
System.out.println("IOEXCeption");
} finally {
try {
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If you are using Java 7, this becomes much easier, since a new try-with syntax was introduced. Then you can write like this:
try(FileInputStream inStream = new FileInputStream("filename.properties")){
properties.load(inStream);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound");
} catch (IOException e) {
System.out.println("IOEXCeption");
}
and the stream is closed automatically.
here is an example:
public class PropertiesHelper {
public static Properties loadFromFile(String file) throws IOException {
Properties properties = new Properties();
FileInputStream stream = new FileInputStream(file);
try {
properties.load(stream);
} finally {
stream.close();
}
return properties;
}
}
You can use Lombok #Cleanup to do it simply.
http://projectlombok.org/features/Cleanup.html
Properties properties = new Properties();
try {
#Cleanup FileInputStream myFis = new FileInputStream("filename.properties");
properties.load(myFis);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound");
}catch (IOException e) {
System.out.println("IOEXCeption");
}
Or, only if your are using Java 7, there is the "try with resource" new feature.
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Properties properties = new Properties();
try (FileInputStream myFis = new FileInputStream("filename.properties")) {
properties.load(myFis);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound");
}catch (IOException e) {
System.out.println("IOEXCeption");
}