Read from internal storage file (Android) - 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
}
}
}

Related

Write exif data to android video files

I am extracting metadata information (Exif infor) by using Id3 library in android, but I am getting null pointer exception and getting null in log Message it is a reason because value in src_set is null .I am not getting why it is returning null. my code is :
File src = new File(pathdata);
MusicMetadataSet src_set = null;
try {
src_set = new MyID3().read(src);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} // read metadata
if (src_set == null) // perhaps no metadata
{
Log.i("NULL", "NULL");
}
else
{
try{
IMusicMetadata metadata = src_set.getSimplified();
String artist = metadata.getArtist();
String album = metadata.getAlbum();
String song_title = metadata.getSongTitle();
Number track_number = metadata.getTrackNumber();
Log.i("artist", artist);
Log.i("album", album);
}catch (Exception e) {
e.printStackTrace();
}
File dst = new File(pathdata);
MusicMetadata meta = new MusicMetadata("name");
meta.setAlbum("Chirag");
meta.setArtist("CS");
try {
new MyID3().write(src, dst, src_set, meta);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ID3WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // write updated metadata
}

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.

Converting string to data

I am getting a duration of my audio file , convert it to int , then convert int to string and then string to something like this 00:32 . Converted string is correct, but then is a problem with convert that string to data
Here is my code:
File file = new File(Environment.getExternalStorageDirectory()+"/MyImages/.audio1.wav");
MediaPlayer mp = new MediaPlayer();
FileInputStream fs = null;
FileDescriptor fd = null;
try {
fs = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fd = fs.getFD();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.setDataSource(fd);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int length = mp.getDuration()/1000;
mp.release();
String audiotime = String.valueOf(length);
SimpleDateFormat sdf = new SimpleDateFormat("mmss");
try {
Date d = sdf.parse(audiotime);
textView1.setText(audiotime);
} catch (ParseException ex) {
}
Two things, most important, you use the original String as text for your TextView. You should do something like textView1.setText(d.toString());
Secondly, you should use "mm:ss" as your format, instead of "mmss".
Note you could also use the format function of SimpleDateFormat. This will return a StringBuffer, which might be more appropriate since you only need the String representation
source: android documentation

read/write an object to file

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.

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??

Categories

Resources