outputFileStream Return Null - java

public void writeUser() {
String userInfo;
FileOutputStream FOS= null;
UserConnector user = new UserConnector(); // this is other class receive data from user
user.modifyUserFromSignUpToDB(); // this method make all data as one string
userInfo = user.getUserInfo(); // get data from the class as string
try {
FOS = openFileOutput("usersInfo.txt", Context.MODE_APPEND);
FOS.write(userInfo.getBytes());
} catch (FileNotFoundException er) {
Log.e("malek", "cann't create file user");
} catch (IOException er) {
Log.e("malek", "cann't write to file user");
} finally {
try {
if (FOS != null) FOS.close();
} catch (IOException er) {
Log.e("malek", "cann't close file");
}
}
}
FOS always return as null, I try to use getApplicationContext(), this, classname.this and still have same problem

Related

How to Adding Restore setting feature by FileinputStream

So I am new in programing and i adding a feature in my app which save all sharedpreference key in value in Device internal data folder by using fileoutputStream like this add all data in map and store in jsonobject
private String maptojson(){
Map<String, ?> map = prf.getAll();
JSONObject object = new JSONObject();
for (Map.Entry<String,?> entry : map.entrySet()){
try {
object.put( entry.getKey(), entry.getValue());
} catch (JSONException e) {
e.printStackTrace();
}
}
return object.toString();
}
Now Use FileOutputStream for write file in internal Storage "data'
public void backupSetting() {
Throwable th;
FileOutputStream fileOutputStream;
IOException e;
FileOutputStream fileOutputStream2 = null;
File externalStorageDirectory = Environment.getExternalStorageDirectory();
if (externalStorageDirectory.exists() && externalStorageDirectory.canWrite()) {
if (externalStorageDirectory.getUsableSpace() >= 1048576) {
File file = new File(externalStorageDirectory.toString() + "/data/MyApp/" + "MyAppSetting.ma");
try {
new File(file.getParent()).mkdirs();
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
try {
fileOutputStream.write(maptojson().getBytes());
fileOutputStream.flush();
fileOutputStream.close();
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
} catch (IOException e3) {
e = e3;
try {
e.printStackTrace();
if (fileOutputStream != null) {
}
} catch (Throwable th2) {
th = th2;
fileOutputStream2 = fileOutputStream;
if (fileOutputStream2 != null) {
try {
fileOutputStream2.close();
} catch (IOException e4) {
e4.printStackTrace();
throw th;
}
}
throw th;
}
}
} catch (IOException e5) {
e = e5;
fileOutputStream = null;
e.printStackTrace();
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e6) {
e6.printStackTrace();
}
}
} catch (Throwable th3) {
th = th3;
if (fileOutputStream2 != null) {
}
try {
throw th;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
}
Now i want to add restore setting means restore setting by using that file "MyAppSetting.ma". I know i can do it by using FileInputStream but I don't understand how to do? please help if you could

Get data from getter method instead of passing in a Bundle

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.

How do I write multiple objects to the serializable file and read them when the program is used again?

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();
}
}
}
}

How to append an object to an existing file (generics)?

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() {}
}

why show me the last object i put in txt

I have a big problem , I write in a txt file same objects Accounts when i click to see all objects i have write in txt is show me the last one only and how i show up the account in JOptionPane , the second is how i can make the account to take nuber one ,two , three...... every account i write to take a number plus one from the precedent account .
I believ to explain apparent
if( str.equals("Receipt") )
{
ObjectInputStream in = null;
Account acc = null;
try
{
in = new ObjectInputStream(new FileInputStream("Accounts.txt"));
while( (acc = (Account) in.readObject()) !=null)
{
if (acc instanceof Account)
((Account)acc).print();
//acc.print();
}
}
catch(EOFException ex)
{
System.out.println("End of file reached.");
}
catch(ClassNotFoundException ex)
{
System.out.println("Error casting");
ex.printStackTrace();
}
catch(FileNotFoundException ex)
{
System.out.println("Error specified file does not exist");
ex.printStackTrace();
}
catch(IOException ex)
{
System.out.println("Error with I/O processes");
ex.printStackTrace();
}
finally
{
try
{
in.close();
}
catch(IOException ex)
{
System.out.println("Another IOException during the closing");
ex.printStackTrace();
}
}
}
code to write object in file
Account ac=new Account(posoOfil,poso,ariLoga,aitiol,diafor);
ac.print();
try{
OutputStream file = new FileOutputStream("Accounts.txt");
OutputStream buffer = new BufferedOutputStream( file );
ObjectOutput output = new ObjectOutputStream( buffer );
try{
output.writeObject(ac);
output.flush();
System.out.println("Object written to file");
}
finally{
output.close();
}
}
catch
(FileNotFoundException ex) {System.out.println("Error with specified file") ;
ex.printStackTrace();}
catch(IOException ex){
System.out.println("Cannot perform output.");
}
}
And the class Account
public class Account implements Serializable {
private int arithmKat;
// private Date date ;
private int posoOfil;
private int posoKat;
private String ariLoga ;
private String aitiol;
private boolean diafor=false;
public Account(int posoOfil, int posoKat,String ariLoga,String aitiol,boolean diafor){
arithmKat++;
this.posoOfil=posoOfil;
this.posoKat=posoKat;
this.ariLoga=ariLoga;
this.aitiol=aitiol;
this.diafor=diafor;
}
void print(){
System.out.println(arithmKat+" "+posoOfil+" "+posoKat+" "+diafor);}
}
You only write one account to the file. There is no loop at all in the code writing the account. Code that would write several accounts would look like this:
private void writeAccounts(List<Account> accounts) throws IOException {
OutputStream file = new FileOutputStream("Accounts.txt");
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
try {
for (Account account : accounts) {
output.writeObject(account);
}
output.close();
}
finally {
output.close();
}
}

Categories