How to read file from phone's internal memory in android? - android

I have downloaded a file from HttpConnection using the FileOutputStream in android and now its being written in phone's internal memory on path as i found it in File Explorer
/data/data/com.example.packagename/files/123.ics
Now, I want to open & read the file content from phone's internal memory to UI. I tried to do it by using the FileInputStream, I have given just filename with extension to open it but I am not sure how to mention the file path for file in internal memory,as it forces the application to close.
Any suggestions?
This is what I am doing:
try
{
FileInputStream fileIn;
fileIn = openFileInput("123.ics");
InputStream in = null;
EditText Userid = (EditText) findViewById(R.id.user_id);
byte[] buffer = new byte[1024];
int len = 0;
while ( (len = in.read(buffer)) > 0 )
{
Userid.setText(fileIn.read(buffer, 0, len));
}
fileIn.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}

String filePath = context.getFilesDir().getAbsolutePath();//returns current directory.
File file = new File(filePath, fileName);
Similar post here
read file from phone memory

If the file is where you say it is, and your application is com.example.packagename, then calling openFileInput("123.ics"); will return you a FileInputStream on the file in question.
Or, call getFilesDir() to get a File object pointing to /data/data/com.example.packagename/files, and work from there.

I am using this code to open file in internal storage. i think i could help.
File str = new File("/data/data/com.xlabz.FlagTest/files/","hello_file.xml");

Related

FileNotFoundException while reading an uploaded file

I'm trying to convert an IOS App to Android. I have no experience in Android so it may be a silly question. Sorry for that:)
I've uploaded some json files into the "files" folder of the emulator by device file explorer. (not into the external storage)
But when reading them, FileNotFoundException is thrown. (Permission denied) The code I used for reading is as below;
try {
File file = new File(getApplicationContext().getFilesDir() + "/Data/Users/profile.json");
FileReader fileReader = new FileReader(file);
String contents = "";
int i;
while((i = fileReader.read())!= -1) {
char ch = (char)i;
contents += ch;
}
return contents;
} catch (IOException e) {
e.printStackTrace();
}
I've tried to form those files programmatically in the same directory under "files" folder, as below.
String string = "{}";
File file = new File(getApplicationContext().getFilesDir() + "/Data/Users");
file.mkdirs();
File file2 = new File(getApplicationContext().getFilesDir() + "/Data/Users/profile.json");
file2.createNewFile();
FileOutputStream fos = new FileOutputStream(file2);
fos.write(string.getBytes());
fos.close();
This time, I managed to read them successfully by using the above code. It seems uploading files by device file explorer leads to some permission problems. I couldn't find how to modify them. How can I fix this?

it works fine on desktop, but not on android. why?

saving socres to highscore.sav file, it works fine on desktop, but not on android. why?
String fileName = "highScores.sav";
file = new File(fileName);
public static void save(){
try{
FileOutputStream fileOut = new FileOutputStream(file);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(gd);
out.close();
}
catch(Exception e){
e.printStackTrace();
System.out.println(e);
Gdx.app.exit();
}
}
public static void load(){
try{
if(!saveFileExists()){
init();
return;
}
FileInputStream fileIn = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fileIn);
gd = (GameData) in.readObject();
in.close();
}
catch(Exception e){
e.printStackTrace();
System.out.println(e);
Gdx.app.exit();
}
}
got error: java.io.FileNotFoundException: /highScores.sav: open failed: EROFS (Read-only file system)
This isn't working because you have not specified a directory to save into. Android has tight restrictions on where an app can write files.
You don't need any permissions to read or write a file to internal memory. But you do need to specify internal memory (called local memory in libgdx).
Libgdx already handles this directly for you so you don't need to differentiate between desktop and Android. This explains exactly how to do it. All you need is the string or bytes you want to write into the file, and the libgdx API's handle the rest.
FileHandle file = Gdx.files.local(filename);
file.writeString(stringToWrite, false);
If you want to continue using your method of writing the file, you can get the path to the file like this:
String fileName = "highScores.sav";
file = new File(Gdx.files.getLocalStoragePath () + "/" + fileName);
Have you added the permission to the android app to allow writing to the storage space?

Android application how to store and get a file inside the application

I have an application that make me choose a file through a file explorer(the file is stored on the sd), and then reads it.
I want to modify it, so it has the file directly into the app and reads the file from "inside". Where I have to put the file into the project? How can I access it?
You can save a file inside your project by using the following code:
File cDir = getApplication().getExternalFilesDir(null);
File saveFilePath = new File(cDir.getPath() + "/" + "yourfilename");
You can see the saved file inside "files" folder of your application package name in your device.
Try the following path in your device:
File manager >> Android >> data >> "your package name" >> files >> new file.
Yes, you can put your file into /assets folder, and retrieve as follows:
AssetManager assetManager = getAssets();
InputStream instream = assetManager.open("file.txt");
or res/raw folder:
InputStream raw = getResources().openRawResource(R.raw.file);
If you want to modify it, you'll be able only to write a file into External storage (e.g. sdcard),
or into Internal storage (under your application folder data/data/package_name/).
If you store your file into External storage it will persist until user manually or programmatically deletes the file. But if you store this file into Internal storage, it will be deleted if user deletes an app, or clear an application cache.
Demo
File myExternalFile;
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
saveToExternalStorage.setEnabled(false);
} else {
myExternalFile = new File(getExternalFilesDir(filepath), filename);
}
save External Storage (FileOutputStream )
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(myInputText.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
myInputText.setText("");
responseText.setText("Saved to External Storage.(StorageFile.txt)");
Get External Storage (FileInputStream )
try {
FileInputStream fis = new FileInputStream(myExternalFile);
BufferedReader br = new BufferedReader(
new InputStreamReader(fis));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
myInputText.setText(myData);
responseText
.setText("Data retrieved from Internal Storage.(StorageFile.txt)");

Android: Correctly downloading/saving an email attachement

I have an interesting problem: My application is designed to send and open up a zip full of files, and the zip has a special extension (easier for the user). I can zip up the files I need to attach in an e-mail, and I can send them.
When I use the g-mail "view" button and select my app to open the file, it doesn't unzip them correctly. However, if I use the gmail "download" button, and then open the file through a file explorer, the file unzips correctly.
This is the code I use to download the attachment:
// get attachment
try {
attachment = getContentResolver().openInputStream(
getIntent().getData());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Save it
try {
File root = Environment.getExternalStorageDirectory();
path = root.getPath() + "/PSattachment.psz";
savedFile = new File(path);
FileOutputStream fos = new FileOutputStream(savedFile, false);
BufferedOutputStream os = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int byteRead = 0;
while ((byteRead = attachment.read(buffer)) != -1) {
os.write(buffer, 0, byteRead);
}
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
Am I doing something wrong? Thanks in advance. (Also, the process of unzipping is the same in both cases [file explorer and view from email], so I'm pretty sure it's something in here. Also, the file DOES download, and is the right size. It just won't unzip).
I found the answer!!! Took a while, but at least it works now:
try {
InputStream attachment = getContentResolver()
.openInputStream(getIntent().getData());
savedFile = new File(Environment
.getExternalStorageDirectory().getAbsolutePath(),
"temp" + System.currentTimeMillis() + ".psz");
FileOutputStream f = new FileOutputStream(savedFile);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = attachment.read(buffer)) > 0) {
f.write(buffer);
}
f.close();
} catch (Exception e) {
}
I just used this code to download the attachment and now everything works perfectly =D
Check this out please:
http://www.jondev.net/articles/Unzipping_Files_with_Android_(Programmatically)
A guide to unzip files in android, hope it helps solve your problem

Reading int value from txt file on SD card android

So in this app I made, The user makes a project and when they save, the number of frames is saved to numberFrames.txt on the SD card. Then I retrieve the file in another class. Only thing is that nFrames = 50 when i show a toast of nFrames to the screen after I run this code. The only initializing of nFrames I do is to zero right above this code, which is located in the onCreate().
File sdcardLocal = Environment.getExternalStorageDirectory();
File dir = new File (sdcardLocal.getAbsolutePath() + "/Flipbook/"+customizeDialog.getTitle()+"/");
dir.mkdirs();
File fileNum = new File(dir, "numberFrames.txt");
FileWriter myFileWriter = null;
try {
myFileWriter = new FileWriter(fileNum);
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter out = new BufferedWriter(myFileWriter);
try {
String text = bitmaps.size()+"";
out.write(text);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
I retrieve the file like this. I have no idea where this "50" value for nFrames came from as there are no loops around this and I know for sure that the particular project saved has only 3 frames. Why is this?
FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream(new File(mFolderDialog.getPath()+"/numberFrames.txt"));
bis = new BufferedInputStream(is);
nFrames = bis.read();
}catch (IOException e) {
e.printStackTrace();
}
You are writing out a string, and then reading the first byte as an integer. 50 is the ascii code for the '2' character.
You can use BufferedReader.readLine to read the entire first line of the file as a String, and then Integer.parseInt to convert that to an integer.
Also, I would take a closer look at your application's workflow. You don't give much information, but saving a file with a single integer value to the sdcard has a certain "smell" to it :). Have you looked at using a database, or maybe store the text file in your application's directory instead?

Categories

Resources