Saving to binary/serialization java - java

I have to, quote on quote,
1.Save accounts to a binary (serialized) file.
2.Load (recreate) accounts from a binary (serialized) file.
So firstly, I was looking up examples of what exactly that is and I am lost, in same scenarios people mention xml, in my head I think it means like 01010011000 (binary), and when I look at other code it looks like a normal text file save.
What exactly does he mean, and can someone post an example, or give me a site that better clarifies this?
Once I see what I actually need to do, I can implement it easily, I'm just confused on what exactly is being saved (data-wise) and how.
*I already have an option to save via textfile (.txt) if I can just use some of that code for this binary part.
Thanks!
Here is what I have now, it's still not working I think.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SerializationMain implements Serializable {
public static void saveSerialized(Object YourObject, String filePath) throws IOException {
ObjectOutputStream outputStream = null;
try {
outputStream = new ObjectOutputStream(new FileOutputStream(filePath + ".dat"));
outputStream.writeObject(YourObject);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static Object loadSerialized(String filePath, Object[][] data1) throws IOException {
try {
FileInputStream fileIn = new FileInputStream(filePath);
ObjectInputStream in = new ObjectInputStream(fileIn);
try {
data1 = (Object[][]) in.readObject();
} catch (ClassNotFoundException ex) {
Logger.getLogger(SerializationMain.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println(data1.length);
return data1;
}
}

Assuming you have a class called "account" you simply need to implements Serializable at the top of your class header.
From my understanding, that will serialize all the data into a binary form. You will need to of course still perform the steps to actually write/read the class object out to a file using ObjectOutputStream/ObjectInputStream.
So for example...
public class account implements Serializable
{ ...
}
Then in your main function for example, where you want to save the object, you would create a File, attach it to an ObjectOutputStream and write out your object in binary form.

First hit on google: http://www.javacoffeebreak.com/articles/serialization/index.html - basically you should serialize your object to a file. Then you can load it into an object again later.

Related

Convert text file data into uppercase in Java

I made the program in java to convert the text in the file in the uppercase but it erases data instead of converting it
But when I take data from 1 file and write converted data into another file, it works fine.
So I got problem that how can I do this using single file.
Here below is my code, Tell me how to correct this?
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
public class uppercase{
public static void main(String[] args) {
try {
FileReader reader = new FileReader("e.txt");
FileWriter writer = new FileWriter("e.txt");
int data;
int data2;
while((data=reader.read())!= -1) {
data2=Character.toUpperCase(data);
writer.write(data2);
}
reader.close();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
this is bad idea, because you are writing to same file you are reading from. You should either:
Load complete file to memory, close it and then dump it to same file.
Save to different file and rename (better)
firstly you open a stream to read from file and append the result to a String variable and at the end of reading, you write all the data to the file:
try {
FileReader reader = new FileReader("e.txt");
String result = "";
int data;
int data2;
while ((data = reader.read()) != -1) {
data2 = Character.toUpperCase(data);
result += (char)data2;
}
reader.close();
System.out.println(result);
FileWriter writer = new FileWriter("e.txt");
writer.write(result);
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Transferring data from input to output File, getting Exception

My data is not getting transferred to the output file , I always get an Exception.
import java.io.*;
import java.util.*;
class TransferData {
public static void main(String[] args) {
String path1="E:\\IO\\Input.txt";
String path2="E:\\IO\\Output.txt";
int data;
System.out.println("Transfering started...");
try {
FileInputStream fis=new FileInputStream(path1);
FileOutputStream fos=new FileOutputStream(path2);
while((data=fis.read())!=-1) {
fos.write(data);
}
}
catch(Exception e) {
System.out.println("exception caught!");
}
System.out.println("Completed...");
}
}
How do I transfer data to output file ?
Tested this code on my local machine it is works without exceptions.
Check is file E:/IO/Input.txt exists.
IS Directory E:/IO is writeable for your user
(If file E:/IO/Output.txt already exists check is it writeable and not opened in another programm)
By code:
It is good practice to close FIS and FOS after programm finished execution.
public class TransferData {
public static void main(String[] args) {
String path1 = "E:\\IO\\Input.txt";
String path2 = "E:\\IO\\Output.txt";
int data;
System.out.println("Transfering started...");
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(path1);
fos = new FileOutputStream(path2);
while ((data = fis.read()) != -1) {
fos.write(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Completed...");
}
}
If you replace System.out.println("exception caught!"); with e.printStackTrace(); then you will get a much more useful error message.
If you then post that error message here, people will be able to help you much more easily.
It could be the case that the program cannot find the file you're trying to read.
I highly suggest to use e.printStackTrace() as the others suggested.
One possible problem might be the filesystem permissions or the file you are trying to read from being not existent.
You might also want to use a "try with resources" to simplify your code.
Your code is missing a close statement for your Streams too.
All together your code would look something like this:
import java.io.*;
import java.util.*;
class TransferData {
public static void main(String[] args) {
String path1="E:\\IO\\Input.txt";
String path2="E:\\IO\\Output.txt";
int data;
System.out.println("Transfering started...");
try (
FileInputStream fis=new FileInputStream(path1);
FileOutputStream fos=new FileOutputStream(path2)
) {
while((data=fis.read())!=-1) {
fos.write(data);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
One last thing, if you post your code on StackOverflow, please do not mix different formatting styles (e.g. { in the same line as an if and sometimes in the next) and try to have the code well formatted from the beginning.
Add e.printStackTrace() to your catch block, and post the data printed in your console here, people will be able to help you better.
The most likely cause of the exception getting thrown is that the system is not able to find the file "E:\\IO\\Input.txt" or "E:\\IO\\Output.txt" make sure that the file's are there and Output.txt is not set to read only.

JAVA - Writing sentences to textfile

I have this code below. Basically I'm getting an input from a given url. This website shows a sentence. Each time I reload the website it gets a new sentence and so on. So, I managed to get that working. Now I'm trying to write the sentence in a textfile. But something is wrong. It only writes the first line and nothing else. What's wrong with my code?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class ReadIp {
public static void main(String[] args) throws MalformedURLException, IOException,
InterruptedException {
ReadIp readIP = new ReadIp();
while (true) {
readIP.getIP();
Thread.sleep(2000);
}
}
BufferedReader buff;
InputStreamReader inStream;
String line;
URL url;
URLConnection urlConn;
FileWriter fileWriter ;
BufferedWriter bufferedWriter;
public ReadIp() throws IOException {
fileWriter = new FileWriter("myfile.txt", true);
bufferedWriter = new BufferedWriter(fileWriter);
}
public void getIP() throws MalformedURLException, IOException {
this.url = new URL("http://test.myrywebsite.co.uk");
this.urlConn = this.url.openConnection();
this.inStream = new InputStreamReader(this.urlConn.getInputStream());
this.buff = new BufferedReader(this.inStream);
try {
while ((this.line = this.buff.readLine()) != null)
{
System.out.println(this.line);
try {
this.bufferedWriter.write(this.line);
this.bufferedWriter.write("\n");
this.bufferedWriter.flush();
} catch (IOException e)
{
}
}
if (this.bufferedWriter != null)
{
this.bufferedWriter.close();
}
this.inStream.close();
}
catch (Exception ex)
{
}
}
}
Any help would be greatly appreciated.
Thank you.
Move the statement
writer.close();
out of the inner try catch block so that you're not closing the OutputStream after writing the first entry to the file. The same applys to the InputStream
inStream.close();
The BufferedWriter is being opened in the constructor and is being closed in getIp. The constructor is called only once, but getIp is called every 2 seconds to read a sentence. So the BufferedWriter is being closed after the first line (and not opened again). The second call of getIp tries to write the second sentence but the BufferedWriter is closed. This should throw an Exception which is being ignored since the catch block is empty.
Never leave a catch block empty - as fgb wrote above!
First of all, at least add a printStackTrace() to each empty catch block, e.g.:
catch (Exception ex) {
ex.printStackTrace();
}
so you can see if an Exception is being thrown...
I would suggest to open the BufferedWriter in the method getIp instead of the constructor; or, if it should stay open all the time, close the BufferedWriter in an additional method, called after the loop in main terminates

Reading serialised object java gives classnotfound exception

Here's my current code:
//export method
public static void exportObj (Object obj, String fname) {
try {
// Serialize data object to a file
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fname));
out.writeObject(obj);
out.close();
} catch (IOException e) {}
}
//import method
public static Object importObj (String fname) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(fname));
return in.readObject();
} catch (IOException e) {}
return new Object();
}
The export function works fine, I think, it turns my User object into a file and saves it, but then when I try to import it, it gives me a ClassNotFound Exception. What is happening?
All the classes you want to deserialize must exist on the CLASSPATH of the project that contains the import code.

Can't serialize an ArrayList

This is a followup to Serializing a vector
I'm trying to implement loading and saving for a game I'm working on.
I want to save a Maze which contains, among other attributes, an ArrayList of Entity.
Entity is a super class for Dragon, Hero and Item. All three of these types can be contained at once in the vector.
Using the "automatic" serialization mechanism (adding implements Serializable to Maze) saves all attributes but the ArrayList.
Why does this happen?
My code is below, for completeness' sake.
package logic;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public final class LoadAndSave {
public static final transient boolean available = false;
public static final boolean serialize(Object obj) {
// Write to disk with FileOutputStream
FileOutputStream saveFile;
try {
saveFile = new FileOutputStream("game.sav");
} catch (FileNotFoundException e) {
return false;
}
// Write object with ObjectOutputStream
ObjectOutputStream objOut;
try {
objOut = new ObjectOutputStream(saveFile);
} catch (IOException e) {
//
return false;
}
// Write object out to disk
try {
objOut.writeObject(obj);
} catch (IOException e) {
return false;
}
return true;
}
public static final Object load() {
FileInputStream fileIn;
try {
fileIn = new FileInputStream("game.sav");
} catch (FileNotFoundException e1) {
return null;
}
// Read object using ObjectInputStream
ObjectInputStream objIn;
try {
objIn = new ObjectInputStream(fileIn);
} catch (IOException e) {
return null;
}
// Read an object
Object obj;
try {
obj = objIn.readObject();
} catch (IOException e) {
return null;
} catch (ClassNotFoundException e) {
return null;
}
return obj;
}
}
Is Entity serializable too? (you mentioned that just Maze is serializable).
And be sure that the list is not defined as transient or static, otherwise it will be skipped by the serialization mechanism.
I checked Your code with the following assumptions:
class Entity implements Serializable {}
and:
private char[][] mazeWalls = new char[0][0];
private Vector<Entity> entities = new Vector<Entity>();
...and it works perfectly, serializing and deserializing empty Entity objects...
You need to make sure that you close your streams. Your code for load() can be simplified to look something like this:
ObjectInputStream objIn = null;
try {
objIn = new ObjectInputStream(new FileInputStream("game.sav"));
return objIn.readObject();
} catch (Exception exception) {
// Deal with errors
return null;
} finally {
if (objIn != null) {
try {
objIn.close();
} catch (Exception exception) {}
}
}
serialise() can be altered in a similar way.

Categories