read/write an object to file - android

here is the code :
my mission is to serialize an my object(Person) , save it in a file in android(privately), read the file later,(i will get a byte array), and deserialize the byta array.
public void setup()
{
byte[] data = SerializationUtils.serialize(f);
WriteByteToFile(data,filename);
}
Person p =null ;
public void draw()
{
File te = new File(filename);
FileInputStream fin = null;
try {
fin=new FileInputStream(te);
byte filecon[]=new byte[(int)te.length()];
fin.read(filecon);
String s = new String(filecon);
System.out.println("File content: " + s);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text(p.a,150,150);
}
and my function :
public void WriteByteToFile(byte[] mybytes, String filename){
try {
FileOutputStream FOS = openFileOutput(filename, MODE_PRIVATE);
FOS.write(mybytes);
FOS.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("done");
}
it is returning a filenotfoundexception .
(i am new at this, so please be patient and understanding)
EDIT ::this is how i am (trying to ) read, (for cerntainly)
ObjectInputStream input = null;
String filename = "testFilemost.srl";
try {
input = new ObjectInputStream(new FileInputStream(new File(new File(getFilesDir(),"")+File.separator+filename)));
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Person myPersonObject = (Person) input.readObject();
text(myPersonObject.a,150,150);
} catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and for reading :::
if(mousePressed)
{
Person myPersonObject = new Person();
myPersonObject.a=432;
String filename = "testFilemost.srl";
ObjectOutput out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+File.separator+filename));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.writeObject(myPersonObject);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

You don't need to use the 'byte array' approach. There is an easy way to (de)serialize objects.
EDIT: here's the long version of code
Read:
public void read(){
ObjectInputStream input;
String filename = "testFilemost.srl";
try {
input = new ObjectInputStream(new FileInputStream(new File(new File(getFilesDir(),"")+File.separator+filename)));
Person myPersonObject = (Person) input.readObject();
Log.v("serialization","Person a="+myPersonObject.getA());
input.close();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Write:
public void write(){
Person myPersonObject = new Person();
myPersonObject.setA(432);
String filename = "testFilemost.srl";
ObjectOutput out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+File.separator+filename));
out.writeObject(myPersonObject);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Person class:
public class Person implements Serializable {
private static final long serialVersionUID = -29238982928391L;
int a;
public int getA(){
return a;
}
public void setA(int newA){
a = newA;
}
}

FileNotFoundException when creating a new FileOutputStream means that one of the intermediate directories didn't exist. Try
file.getParentFile().mkdirs();
before creating the FileOutputStream.

Add this code to manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
Go to phone setting/applications/your_app/permissions/ allow files and media permission. You can ask permission via by code and when user enter app program will ask permission. If you want I can give you code.
All writen and readen objects must be serializable.(Must implements Serializable interface) If A class extends B class, to set B class serializable is enough.
And add this code to writen and readen class:
private static final long serialVersionUID = 1L;
Write to external memory:
public static void writeToExternal(Serializable object, String filename) {
try {
//File root = new File(Environment.getExternalStorageDirectory(), "MyApp");
//or
File root = new File("/storage/emulated/0/MyApp/");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, filename);
FileOutputStream fos = new FileOutputStream(file);
ObjectOutput out = new ObjectOutputStream(fos);
out.writeObject(object);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to write to internal memory(This memory is not visible and doesn't need permission. This is your app stored in. For this, you can use getFilesDir() instead of getExternalStorageDirectory(). More about https://developer.android.com/reference/android/content/ContextWrapper#getFilesDir%28%29
https://developer.android.com/reference/android/os/Environment.html#getDataDirectory%28%29
https://gist.github.com/granoeste/5574148
https://source.android.com/docs/core/storage
public static void writeToInternal(Context context, Serializable object, String filename){
try {
//File root1 = new File(context.getFilesDir(), "MyApp");
//or
File root = new File("/data/user/0/com.example.myapplication/files/MyApp/");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, filename);
FileOutputStream fos = new FileOutputStream(file);
ObjectOutput out = new ObjectOutputStream(fos);
out.writeObject(object);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Read an object:
public static Object read(String filename) {
try {
File file = new File("/storage/emulated/0/MyApp/" + filename);
FileInputStream fis = new FileInputStream(file);
ObjectInputStream input = new ObjectInputStream(fis);
Object data = (Object) input.readObject();
input.close();
return data;
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
When you call read method you must cast to your readen and writen class.(For example Person p = (Person)read("file.txt");
Import all classes and run.

Related

android how to read data using internal storage

public void loadprev()
{
String tempread;
try {
FileInputStream fis = openFileInput("data.gds");
try {
fis.read(tempread.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
my program crashes upon trying to execute fis.read(tempread.getBytes());
i want to read the first line in data.gds and put it into a string, how can i do this?
and no, im not going to use SharedPreferences
add a string buffer and then read from it everyline will be put in the Stringbuffer, then you can retrieve the line from that buffer.
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];
while ((n = fis.read(buffer)) != -1)
{
fileContent.append(new String(buffer, 0, n));
}
Also, if you are not catching exceptions properly, surround them in 1 try catch, but try to catch them in the future:
{
String tempread;
try {
FileInputStream fis = openFileInput("data.gds");
fis.read(tempread.getBytes());
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
now your code is easier to read.

How to save music files from raw folder into sdcard in android

Hi i need to save array of music files into sdcard i tried using below code only folder is creating in sdcard in side folder no music files is saving any one suggest me where i did mistake...
FillesaveActivity.class:
public class FillesaveActivity extends Activity {
/** Called when the activity is first created. */
public static ArrayList<Integer> list1 = new ArrayList<Integer>();
Integer[] text;
int cnt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list1.add(R.raw.intro_letter_report_card);
list1.add(R.raw.intro_title_page2);
text = list1.toArray(new Integer[list1.size()]);
for(int i=0;i<text.length;i++)
{
cnt++;
File sd = Environment.getExternalStorageDirectory();
File folDirectory = new File("/sdcard/Songsnew1/");
// have the object build the directory structure, if needed.
folDirectory.mkdirs();
File source = new File(""+text[i]);
File destination= new File(folDirectory, "song"+cnt+".mp3");
if(source.exists()){
try {
FileChannel src = new FileInputStream(source).getChannel();
FileChannel dst = new FileOutputStream(destination).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
Use Like this:
list1.add(R.raw.intro_letter_report_card);
list1.add(R.raw.intro_title_page2);
for(int name : list1)
{
cnt++;
InputStream stream = null;
File direct = new File(Environment.getExternalStorageDirectory() + "/Songsnew1");
if(!direct.exists())
{
if(direct.mkdir()); //directory is created;
}
stream = getResources().openRawResource(name);
String outFileName = Environment.getExternalStorageDirectory() + "/Songsnew1/song1"+cnt+".mp3";
OutputStream myOutput = null;
try
{
myOutput = new FileOutputStream(outFileName);
}
catch (FileNotFoundException e2)
{
// TODO Auto-generated catch block
e2.printStackTrace();
}
// transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
try
{
while ((length = stream.read(buffer)) > 0)
{
try
{
myOutput.write(buffer, 0, length);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Close the streams
try
{
myOutput.flush();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
try
{
myOutput.close();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
try
{
stream.close();
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
Hope this will help you.

data not sent using bluetooth socket (android)

I am trying to send a file using Android bluetooth sockets. I am getting the pairing requests but unfortunately the data is not being transferred
my Server side and client side is as follows:
Server: (for my application server is receiving the data)
public void run() {
super.run();
BluetoothAdapter mBtadapter = BluetoothAdapter.getDefaultAdapter();
Log.i("bluetooth Adapter", "got adapter "+ mBtadapter.getAddress());
try {
Ssocket = mBtadapter.listenUsingRfcommWithServiceRecord("CardXchange", uuid);
Log.i("Socket", "Socket Acquired "+ Ssocket.toString());
} catch (IOException e) {
e.printStackTrace();
}
while(true){
if(read_flag()==1){
try {
Toast.makeText(c, "flag is eventually 1", Toast.LENGTH_LONG).show();
Ssocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
try {
client_socket = Ssocket.accept();
if(client_socket!=null){
//this function is used to handle the connection when sockets get connected
manageConnection1(client_socket);
Ssocket.close();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("breaked ", "oh god!! out of the loop ");
}
//implementation of the function
private void manageConnection1(BluetoothSocket client_socket2) {
// TODO Auto-generated method stub
int bytes;
Log.i("serevr chya manage connection madhe gela", "in servers manage connection ");
File file = new File("/sdcard/myfolder/received.Xcard");
try {
FileOutputStream fos = new FileOutputStream(file);
try {
InputStream is = client_socket2.getInputStream();
while((bytes = is.read(buffer, 0, 1024))>0){
fos.write(buffer, 0, 1024);
}
is.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
client_socket2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and the client side (the sending side is like this):
public void run(){
try {
Method m = send_dev.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
Csocket = (BluetoothSocket) m.invoke(send_dev, 1);
Csocket.connect();
manageSendConnection(Csocket);
}catch(Exception e){
e.printStackTrace();
}
}
//function to handle after connection is established.
private void manageSendConnection(BluetoothSocket csocket) {
// TODO Auto-generated method stub
File f = new File("/sdcard/myfolder/card3.Xcard");
byte[] buffer = new byte[(int)f.length()];
try {
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(buffer, 0, (int)f.length());
OutputStream os = csocket.getOutputStream();
os.write(buffer);
os.close();
fis.close();
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
csocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am getting the pairing request but the data is not being sent.
can anyone please help me to find the problem and give a hint on solution??

Read from internal storage file (Android)

How to read the particular data from the internal storage file.
For eg., I have stored
1. Device 2. Time(epoch format) 3. button text
CharSequence cs =((Button) v).getText();
t = System.currentTimeMillis()/1000;
s = cs.toString();
buf = (t+"\n").getBytes();
buf1 = (s+"\n").getBytes();
try {
FileOutputStream fos = openFileOutput(Filename, Context.MODE_APPEND);
fos.write("DVD".getBytes());
fos.write(tab.getBytes());
fos.write(buf);
fos.write(tab.getBytes());
fos.write(buf1);
//fos.write(tab.getBytes());
//fos.write((R.id.bSix+"\n").getBytes());
fos.write(newline.getBytes());
//fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
then while reading, how can we read only price from the file? (using fos.read())
Thanks
I would suggest writing the file in a more structured way, like this:
long t = System.currentTimeMillis()/1000;
String s = ((Button) v).getText();
DataOutputStream dos = null;
try {
dos = new DataOutputStream(openFileOutput(Filename, Context.MODE_APPEND));
dos.writeUTF("DVD");
dos.writeLong(t); // Write time
dos.writeUTF(s); // Write button text
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
// Ignore
}
}
}
To read it back, something like this:
DataInputStream dis = null;
try {
dis = new DataInputStream(openFileInput(Filename));
String dvd = dis.readUTF();
long time = dis.readLong();
String buttonText = dis.readUTF();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
// Ignore
}
}
}

Reading my Serialized Object from File in Android

This is my first attempt at serializing/deserializing objects on any platform and, to put it mildly, I'm confused.
After implementing Serializable to my game object I output it to a file thus:
public void saveGameState(){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(theGame);//theGame is an instance of the custom class
//TGame which stores game info.
byte[] buf = bos.toByteArray();
FileOutputStream fos = this.openFileOutput(filename,
Context.MODE_PRIVATE);
fos.write(buf);
fos.close();
} catch(IOException ioe) {
Log.e("serializeObject", "error", ioe);
}
File f =this.getDir(filename, 0);
Log.v("FILE",f.getName());
}
This seems to work, in that I get no exceptions raised. I can only know for sure when I deserialize it. Which is where things go pear shaped.
public God loadSavedGame(){
TGame g=null;
InputStream instream = null;
try {
instream = openFileInput(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
try {
ObjectInputStream ois = new ObjectInputStream(instream);
try {
g= (TGame) ois.readObject();
return g;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
I got the basis of this code from here Android Java -- Deserializing a file on the Android platform and tried to modify it for my app. When running I get
05-31 23:30:45.493: ERROR/copybit(1279): copyBits failed (Invalid argument)
When the output should be loaded and the saved game start up from when it was saved.
Any help would be appreciated.
The error you've shown is not at all related to serialization: its actually a video display error. I'd suggest looking at the object BEFORE you serialize to make sure its not null, and I'd also suggest serializing to a file on the SD card to make sure you actually had data output (so use new FileOutputStream("/mnt/sdcard/serializationtest") as the output stream and new FileInputStream("/mnt/sdcard/serializationtest") as the input stream) while you are debugging; you can switch back to the context methods after it works, but make sure your sdcard is plugged in while you are doing this.
Finally, modify your logging to look like this:
try {
ObjectInputStream ois = new ObjectInputStream(instream);
try {
g= (TGame) ois.readObject();
return g;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
android.util.Log.e("DESERIALIZATION FAILED (CLASS NOT FOUND):"+e.getMessage(), e);
e.printStackTrace();
return null;
}
} catch (StreamCorruptedException e) {
android.util.Log.e("DESERIALIZATION FAILED (CORRUPT):"+e.getMessage(), e);
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
android.util.Log.e("DESERIALIZATION FAILED (IO EXCEPTION):"+e.getMessage(), e);
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
and see what error gets returned. I expect the serialization is failing somehow.
To seralize or deserialize anything you can use SIMPLE api. It is very easy to use. Download the file and use it in your program
Have a look here
http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#deserialize
Thanks Deepak
I have created below class to do the save and retrieve object.
public class SerializeUtil {
public static <T extends Serializable> void saveObjectToFile(Context context, T object, String fileName){
try {
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(object);
os.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static<T extends Serializable> T getObjectFromFile(Context context, String fileName){
T object = null;
try {
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
object = (T) is.readObject();
is.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return object;
}
public static void removeSerializable(Context context, String filename) {
context.deleteFile(filename);
}
}

Categories

Resources