why show me the last object i put in txt - java

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

Related

outputFileStream Return Null

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

Deserializing an Object only reads one data

how do read file data from file/Deserializing an object.I have created a file which is binary file which contains list of companies data i am able to add new company and its related data but when i want to read back all the file datas it only gives first company datas and it prints null ..what is the problem below is what i have done
public class CompanyInfo extends Company {
int counter=0;
Scanner in=new Scanner(System.in);
private ArrayList<Company> companyinfo;
public CompanyInfo() {
companyinfo=new ArrayList<Company>();
}
public void registercompany() {
System.out.println("Enter Company Name \n");
companyName=in.nextLine();
System.out.println("\n");
System.out.println("Enter Company Code \n");
companyCode=in.nextLine();
System.out.println("\n");
System.out.println("Enter the Share Number \n");
shareNo=in.nextInt();
System.out.println("\n");
System.out.println("Enter Closing Rate \n");
closingRate=in.nextDouble();
Company cin=new Company(companyName,companyCode,shareNo,closingRate);
companyinfo.add(cin);
try {
ObjectOutputStream outObjFile =new ObjectOutputStream(new FileOutputStream("companies.dat",true));
Company company = new Company(companyName,companyCode,shareNo,closingRate);
outObjFile.writeObject(company);
outObjFile.writeChars("\n");
outObjFile.close();
} catch (Exception e) {
// TODO: handle exception
System.out.println("A file error has occurred. Sorry.");
System.out.println( e.getMessage() );
}
counter++;
}
public void viewcompany(){
try {
ObjectInputStream inObjFile = new ObjectInputStream(
new FileInputStream("companies.dat"));
System.out.println(inObjFile.readObject()); // displays first object
Company company = (Company)inObjFile.readObject(); // restores object
System.out.println(company); // displays restored object
inObjFile.close(); // finished with the file now.
} catch (Exception e) {
System.out.println(e.getMessage());
}
I will do two different ways.
Add all details into hashmap and serialize that object. So while reading back, I can search using "key". Key can be name or ID of company. You can do same with ArrayList as well. Search may be difficult. Immutable collections from Guava are less memory used and more better.
Another solution is create object file with key.dat and put into a directory called company. So easy to read back and do search as well.
finally i found the answer ...Hope it helps to others too..good luck
public class CompanyInfo extends Company {
int counter=0;
private static String filename = "company.dat";
Scanner in=new Scanner(System.in);
private ArrayList<Company> companyinfo;
public CompanyInfo() {
companyinfo=new ArrayList<Company>();
}
public void registercompany() {
System.out.println("Enter Company Name \n");
companyName=in.nextLine();
System.out.println("Enter Company Code \n");
companyCode=in.nextLine();
System.out.println("Enter the Share Number \n");
shareNo=in.nextInt();
System.out.println("Enter Closing Rate");
closingRate=in.nextDouble();
Company cin=new Company(companyName,companyCode,shareNo,closingRate);
companyinfo.add(cin);
File file=new File(filename);
boolean append=true;
ObjectOutputStream out=null;
try {
if (!file.exists()||!append) {
out=new ObjectOutputStream(new FileOutputStream(filename));
}
else
{
out=new AppendableObjectOutputStream(new FileOutputStream (filename, append));
}
Company company = new Company(companyName,companyCode,shareNo,closingRate);
out.writeObject(company);
out.flush();
} catch (Exception e){
e.printStackTrace ();
}finally{
try{
if (out != null) out.close ();
}catch (Exception e){
e.printStackTrace ();
}
}
counter++;
}
public void viewcompany(){
try {
List<Object> results = new ArrayList<Object>();
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
try{
while (true) {
results.add(ois.readObject());}
}
catch (OptionalDataException e) {
if (!e.eof) throw e; }
finally {
System.out.println(results);
//System.out.println(((Company)results.get(0)).companyName);
ois.close(); }
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
private static class AppendableObjectOutputStream extends ObjectOutputStream {
public AppendableObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
#Override
protected void writeStreamHeader() throws IOException {}
}
}

Serialized object java

Today I started using serialized object in java, I'm new at it and I have some problems when I try to deserialize.
I have this file where I write all my Account objects, it writes fine I guess. The problem is I don't know how to refer to a specific object from that file, or how could I get all of them into a list? and then refer to it.
This is how i'm trying to read them:
public void readAccount(Account e) {
/* List<Account> results = new ArrayList<Account>();
try {
FileInputStream fileIn = new FileInputStream("test.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
for (int i = 0; i < accBank.size(); i++) {
results.add((Account) in.readObject());
}
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
for (Account acc : results) {
System.out.println(toString(acc));
if(e.getAcc_no() == acc.getAcc_no())
{System.out.println("Deserialized Account...");
System.out.println(toString(e));
}
}
*/
List<Account> results = new ArrayList<Account>();
Account acc = null;
FileInputStream fis = null;
try {
fis = new FileInputStream("test.txt");
while (true) {
ObjectInputStream ois = new ObjectInputStream(fis);
results.add((Account) ois.readObject());
acc = (Account) ois.readObject();
}
} catch (Exception ignored) {
// as expected
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
System.out.println("results = " + results);
for (Account ac : results) {
System.out.println(toString(ac));
if(e.getAcc_no() == ac.getAcc_no())
{System.out.println("Deserialized Account...");
System.out.println(toString(e));
}
}
}
And this is how I write them:
public void writeAccount(Account e) {
try {
ObjectOutputStream os1 = new ObjectOutputStream(
new FileOutputStream("test.txt", true));
os1.writeObject(e);
os1.close();
} catch (Exception exc) {
exc.printStackTrace();
}
}
Edit:
public void writeFile() {
for (int i = 0; i < accBank.size(); i++) {
writeAccount(retAcc(i));
}
}
Can any of you tell me what im doing wrong? I also tried other examples from other questions and didn't work.
What you're doing wrong is that you use several ObjectOutputStreams to write to the same file (which is not a txt file, BTW, since it contains binary data), and use a single ObjectInputStream to read all the accounts. As a consequence, a new serialization header is written each time you write an account, and the ObjectInputStream doesn't expect that.
The best way to write a list of accounts is to do just that: you store the accounts into a List<Account>, and write the list. To read the list of accounts, you do just that: you read a single object from the file, and cast it to List<Account>.

Can't create ObjectInputStream

Why can't I create an ObjectInputStream object? Every time I try to create one I get EOFException and I can't figure why. Can someone help me?
Below is the code with which I have the problem and the stack trace obtained from the execution. The file is empty.
public void loadFromFileStudent() throws IOException, ClassNotFoundException {
try{
InputStream inputStream = new FileInputStream("student.txt");
System.out.println(inputStream.toString());
ObjectInputStream objectInputStream;
objectInputStream = new ObjectInputStream(inputStream);
System.out.println(objectInputStream.toString());
this.repo=(Dictionary<Integer, Student>) objectInputStream.readObject();
objectInputStream.close();
inputStream.close();
}catch (EOFException e){
e.printStackTrace();;
//System.out.println(e.getMessage());
}
}
.
java.io.FileInputStream#65ddcac5
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2324)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2793)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:799)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at repository.Repository.loadFromFileStudent(Repository.java:94)
at repository.Repository.<init>(Repository.java:112)
at utils.DataStructure.createRepository(DataStructure.java:16)
at controller.Controller.<init>(Controller.java:9)
at utils.DataStructure.createController(DataStructure.java:20)
at application.RunMenu.<init>(RunMenu.java:15)
at application.App.main(App.java:5)
EOFException is thrown when end-of-file is reached. That is, you have read the whole file. Therefore you should not close your streams within the try statement, but use try-with-resources to automatically close them.
Try something simple like this:
public void loadFromFileStudent() throws IOException, ClassNotFoundException {
try (InputStream inputStream = new FileInputStream("student.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
this.repo = (Dictionary<Integer, Student>) objectInputStream.readObject();
} catch (FileNotFoundException e) {
System.out.println ("File not found");
} catch (IOException e) {
System.out.println ("Error while reading");
} catch (ClassNotFoundException e) {
System.out.println ("No class");
} catch (ClassCastException e) {
System.out.println ("Could not cast to class");
}
}
Writing is equally simple:
public void writeObject ( Object o ) {
try (FileOutputStream fos = new FileOutputStream ( this.filename );
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(o);
oos.flush();
} catch (NotSerializableException e) {
System.out.println ("Object wont be serialized");
e.printStackTrace();
} catch (IOException e) {
System.out.println ("Error while writing to file");
e.printStackTrace();
}
}
From my understanding of the question I assume OP is doing some thing like below, and which should works. May be OP would have missed something during writing/reading. Hope this helps to figure out.
public class Test2 {
public static void main(String[] args) {
Test2 t = new Test2();
t.create();
t.read();
}
public void create(){
try{
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("D:\\test\\ab.txt"));
Student st = new Student("chevs");
Dictionary<Integer, Student> dict = new Hashtable<Integer, Student>();
dict.put(1, st);
os.writeObject(dict);
}catch(Exception e){
e.printStackTrace();
}
}
public void read()
{
try{
InputStream inputStream = new FileInputStream("D:\\test\\a.txt");
System.out.println(inputStream.toString());
ObjectInputStream objectInputStream;
objectInputStream = new ObjectInputStream(inputStream);
System.out.println(objectInputStream.toString());
private Dictionary<Integer, Student> repo=(Dictionary<Integer, Student>) objectInputStream.readObject();
System.out.println(repo.get(1));
objectInputStream.close();
inputStream.close();
}catch (Exception e){
e.printStackTrace();;
}
}
public class Student implements Serializable{
public String name=null;
public Student(String name){
this.name=name;
}
public String toString() {
return name.toString();
}
}
}

Java - passing input into external C/C++ application

I'm trying to enter some value in external application using Java.
Java application looks like this:
Runtime runtime = Runtime.getRuntime();
// ... str build ...
proc = runtime.exec(str);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
bw.write(value);
bw.flush();
bw.close();
if (proc.waitFor() != 0)
// error msg
// the end
Application hangs at waitFor method.
External application looks like this:
welcome banner
please enter 8 character input:
Welcome banner is printed using printf and input is taken with SetConsoleMode/ReadConsoleInput. ReadConsoleInput reads one char and they are masked with * character.
Help
you can use:
proc.getOutputStream().write("some date".getBytes())
keep in mind that you HAVE to read everything the app send to stdout and stderr, else it might get stuck writing there.
I use a generic class to read it in a different thread.
usage is like:
InputStreamSucker inSucker = new InputStreamSucker(proc.getInputStream());
InputStreamSucker errSucker = new InputStreamSucker(proc.getErrorStream());
proc.waitFor();
int exit = process.exitValue();
inSucker.join();
errSucker.join();
InputStreamSucker code is here:
public class InputStreamSucker extends Thread
{
static Logger logger = Logger.getLogger(InputStreamSucker.class);
private final BufferedInputStream m_in;
private final ByteArrayOutputStream m_out;
private final File m_outFile;
public InputStreamSucker(InputStream in) throws FileNotFoundException
{
this(in, null);
}
public InputStreamSucker(InputStream in, File outFile) throws FileNotFoundException
{
m_in = new BufferedInputStream(in, 4096);
m_outFile = outFile;
m_out = new ByteArrayOutputStream();
start();
}
#Override
public void run()
{
try
{
int c;
while ((c = m_in.read()) != -1)
{
m_out.write(c);
}
}
catch (IOException e)
{
logger.error("Error pumping stream", e);
}
finally
{
if (m_in != null)
{
try
{
m_in.close();
}
catch (IOException e)
{
}
}
try
{
m_out.close();
}
catch (IOException e)
{
logger.error("Error closing out stream", e);
}
if (m_outFile != null)
{
byte data[] = m_out.toByteArray();
if (data.length > 0)
{
FileOutputStream fo = null;
try
{
fo = new FileOutputStream(m_outFile);
fo.write(data);
}
catch (IOException e)
{
logger.error("Error writing " + m_outFile);
}
finally
{
try
{
if (fo != null) fo.close();
}
catch (IOException e)
{
logger.error("Error closing " + m_outFile);
}
}
}
}
}
}
public String getOutput()
{
return new String(m_out.toByteArray());
}
}
Got the answer! The trick is to use WriteConsoleInput() API because program expects keyboard event, not text ... That's why the waitFor() waited forever! :)

Categories