How create multiple serialization? - java

How create multiple serialization ? Now the system write just last record to txt. I want create simple DB that will contain customers info. And what you think, about this method of storing data in txt. ?
private static void WriteCustomers(){
System.out.println("|______Registration module______|");
try {
System.out.println("First name: ");
String firstName = reader.readLine();
System.out.println("Last name: ");
String lastName = reader.readLine();
.....
CustomerManagement obj = new CustomerManagement();
CustomerManagementD customerManagementD = new CustomerManagementD();
customerManagementD.setFirstName(firstName);
customerManagementD.setLastName(lastName);
.....
obj.serializeCustomers(customerManagementD);
}catch (IOException e){
e.getMessage();
}
}
public void serializeCustomers(CustomerManagementD customerManagementD) {
FileOutputStream fout = null;
ObjectOutputStream oos = null;
try {
fout = new FileOutputStream("CustomerManagement.txt");
oos = new ObjectOutputStream(fout);
oos.writeObject(customerManagementD);
System.out.println("Done");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (fout != null) {
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Last question, If I use serialization, I will be able to Edit and Remove stored particular objects?

A txt-file is used for text-only. The ObjectOutputStream stores more than then fields: it stores the classname (and serialVersionUID if present). Try to use .dat what is a generic extension for databases or datas.
You call the method serializeCustomers where Customers is plural and let me think we can store multiple Customer, but the parameter does not allow to use multiple customers. Instead, I suggest, to store a Set (like a LinkedHashSet) to store multiple customers, and yes, you can read and write to the LinkedHashSet.

SOLUTION
private static void WriteCustomers(List<CustomerManagementD> list){
try {
System.out.println("First name: ");
String firstName = reader.readLine();
System.out.println("Last name: ");
String lastName = reader.readLine();
.....
// serialize collection of customers
customerManagementDArraysList.add(new CustomerManagementD(
customerID,firstName,lastName,email,contactNo));
ObjectOutputStream outStream = null;
try {
outStream = new ObjectOutputStream(new FileOutputStream(file));
for (CustomerManagementD p : list) {
outStream.writeObject(p);
}
} catch (IOException ioException) {
System.err.println("Error opening file.");
} finally {
try {
if (outStream != null)
outStream.close();
} catch (IOException ioException) {
System.err.println("Error closing file.");
}
}
}else if (finalcheck.equals("2")){
Adminswitch();
}
System.out.println("|______Customer was successfully saved______|\n Press 'Enter' to continue...");
String absentinput = reader.readLine();
Adminswitch();
}catch (IOException e){
e.printStackTrace();
}
}
private static ArrayList ViewCustomer(){
try{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream oos =new ObjectInputStream(fis);
ArrayList<CustomerManagementD> customerManagementDArraysList = new ArrayList<>();
try {
while (true) {
CustomerManagementD cmd = (CustomerManagementD) oos.readObject();
customerManagementDArraysList.add(cmd);
}
}catch (EOFException e){
e.getMessage();
}
{
while (file.canRead()){
for (CustomerManagementD cmd : customerManagementDArraysList) {
System.out.println("Customer ID: " + cmd.getCustomerID() +
" First Name: " + cmd.getFirstName() +
" Last Name: " + cmd.getLastName()+....);
}
break;
}
}
}catch (IOException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();}
return null;
}

Related

FileInputStream fails on properties file

This properties file in PROJECT/resources/properties.properties can be read and show its content with:
public void showFileContent(String fileName){
File file = new File (fileName);
FileInputStream input = null;
if(file.exists()){
int content;
try {
input = new FileInputStream(fileName);
while ((content = input.read()) != -1) {
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (input != null) {
try {
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}else{
System.out.println("Error : properties File " + fileName + " not found");
}
}
But it fails with a null pointer exception at properties.load with that code
public Properties getProperties(String fileName, Properties properties){
File file = new File (fileName);
InputStream input = null;
if(file.exists()){
try {
input = new FileInputStream(fileName);
properties.load(input);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}else{
System.out.println("Error : properties File " + fileName + " not found");
}
return properties;
}
even when input is set to
input = this.getClass().getClassLoader().getResourceAsStream(fileName)
anyone knows why that can be for a properties text file at the same path for both methods ?
Since the first code snippet works, it seems properties is passed as null to the getProperties() method, resulting in NullPointerException.
Ideally, we shouldn't be passing the properties at all. We just need to create a new object and return it.

How to write all JSON objects from a for loop into a text file using java

I am trying to save all my results from JSON into a text file. However, my for loop seems to be only saving the last result from the loop to the text file. It is obviously just re-writing the result each time into the file. I want to be able to save all the results from the for loop before it saves the file.
List<Status> statuses = null;
Query query = new Query("football");
query.setCount(100);
query.lang("en");
int i=0;
try {
QueryResult result = twitter.search(query);
ArrayList tweets = new ArrayList();
for( Status status : result.getTweets()){
System.out.println("#" + status.getUser().getScreenName() + ":" + status.getText());
String rawJSON = TwitterObjectFactory.getRawJSON(status);
String statusfile = "results.txt";
storeJSON(rawJSON, statusfile);
i++;
}
System.out.println(i);
}
catch(TwitterException e) {
System.out.println("Get timeline: " + e + " Status code: " + e.getStatusCode());
}
} catch (TwitterException e) {
if (e.getErrorCode() == 88) {
System.err.println("Rate Limit exceeded!!!!!!");
try {
long time = e.getRateLimitStatus().getSecondsUntilReset();
if (time > 0)
Thread.sleep(100);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
private static void storeJSON(String rawJSON, String fileName) throws IOException {
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
fos = new FileOutputStream(fileName);
osw = new OutputStreamWriter(fos, "UTF-8");
bw = new BufferedWriter(osw);
bw.write(rawJSON);
bw.flush();
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException ignore) {
}
}
if (osw != null) {
try {
osw.close();
} catch (IOException ignore) {
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException ignore) {
}
}
}
}
}
The method at the bottom called storeJSON is where the work is being done.
Have you tried using a FileWriter with append mode ?
private static void storeJSON(String rawJSON, String fileName) throws IOException {
FileWriter fileWriter = null;
try
{
fileWriter = new FileWriter(fileName, true);
fileWriter.write(rawJSON);
fileWriter.write("\n");
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
} finally {
if(fileWriter!=null) {
fileWriter.close();
}
}
}

FileOutputStream creates a file, but FileInputStream

I am using a FileOutputStream to create a file in an activity that is not my MainActivity. The file is created, and when I destroy the activity, the data I want is written, but when I relaunch the activity from my MainActivity, the file cannot be found. What can I change in my code so that I don't get a fileNotFoundException? The relevant code is here:
try {
fis = new FileInputStream("words");
ois = new ObjectInputStream(fis);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
EOFException eof = null;
int counter = 0;
if (fnfexception == null) {
while (eof == null) {
try {
if (words == null) words = new Dict[1];
else words = Arrays.copyOf(words, counter + 1);
words[counter] = (Dict) ois.readObject();
counter++;
} catch (EOFException end) {
eof = end;
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
}
wordStartCount = counter;
wordCount = counter;
fnfexception = null;
try {
fos = openFileOutput("words", Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
You used wrong way to read from an internal file, use the following code
try {
FileInputStream fis = context.openFileInput("file_name");
int content;
StringBuilder str = new StringBuilder();
while ((content = fis.read()) != -1)
str.append((char) content);
fis.close();
String savedText = str.toString();
} catch (IOException e) {
e.printStackTrace();
}

Java save/load on game - will not compile. (cannot find method)

I have created a save and a load function for my game,however, it refuses to load. (This is my first dealing with save/restore functionality).
It seems to save and by that i mean a 'minesweepersavestate.ser' file appears in my folder but there is an error loading, the error lies in the for (Enumeration e = b.keys(); e.hasMoreElements(); ) { line. It wont compile because it says 'cannot find sysmbol - method keys', i have imported java.util.*.
Could anyone tell me where my error is so i can get these functions working, thank you.
public void saveGame(){
GameBoard b = new GameBoard();
try {
System.out.println("Creating File/Object output stream...");
FileOutputStream fileOut = new FileOutputStream("minesweepersavestate.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
System.out.println("Writing GameBoard Object...");
out.writeObject(b);
System.out.println("Closing all output streams...\n");
out.close();
fileOut.close();
} catch(FileNotFoundException e) {
System.out.println("Class not found\n");
e.printStackTrace();
} catch (IOException e) {
System.out.println("no");
e.printStackTrace();
}
}
public void LoadBoard()
{
GameBoard b = null;
try {
System.out.println("Creating File/Object input stream...");
FileInputStream fileIn = new FileInputStream("minesweepersavestate.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
System.out.println("Loading GameBoard Object...");
b = (GameBoard)in.readObject();
System.out.println("Closing all input streams...\n");
in.close();
fileIn.close();
} catch (ClassNotFoundException e) {
System.out.println("Class not found\n");
e.printStackTrace();
} catch(FileNotFoundException e) {
System.out.println("File not found\n");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Printing out loaded elements...");
for (Enumeration e = b.keys(); e.hasMoreElements(); ) {
Object obj = e.nextElement();
System.out.println(" - Element(" + obj + ") = " + b.get(obj));
}

reading objects from file

I have a problem with reading objects from file Java.
file is anarraylist<projet>
This is the code of saving objects :
try {
FileOutputStream fileOut = new FileOutputStream("les projets.txt", true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for (projet a : file) {
out.writeObject(a);
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
And this is the code of reading objects from file ::
try {
FileInputStream fileIn = new FileInputStream("les projets.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
while (in.available() > 0){
projet c = (projet) in.readObject();
b.add(c);
}
choisir = new JList(b.toArray());
in.close();
} catch (Exception e) {
e.printStackTrace();
}
Writing is working properly. The problem is the reading... it does not read any object (projet) What could be the problem?
As mentioned by EJP in comment and this SO post . if you are planning to write multiple objects in a single file you should write custom ObjectOutputStream , because the while writing second or nth object header information the file will get corrupt.
As suggested by EJP write as ArrayList , since ArrayList is already Serializable you should not have issue. as
out.writeObject(file) and read it back as ArrayList b = (ArrayList) in.readObject();
for some reason if you cant write it as ArrayList. create custome ObjectOutStream as
class MyObjectOutputStream extends ObjectOutputStream {
public MyObjectOutputStream(OutputStream os) throws IOException {
super(os);
}
#Override
protected void writeStreamHeader() {}
}
and change your writeObject as
try {
FileOutputStream fileOut= new FileOutputStream("les_projets.txt",true);
MyObjectOutputStream out = new MyObjectOutputStream(fileOut );
for (projet a : file) {
out.writeObject(a);
}
out.close();
}
catch(Exception e)
{e.printStackTrace();
}
and change your readObject as
ObjectInputStream in = null;
try {
FileInputStream fileIn = new FileInputStream("C:\\temp\\les_projets1.txt");
in = new ObjectInputStream(fileIn );
while(true) {
try{
projet c = (projet) in.readObject();
b.add(c);
}catch(EOFException ex){
// end of file case
break;
}
}
}catch (Exception ex){
ex.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Categories

Resources