My app can't open internal storage file - android

Android app: Newly created files on internal storage appear in the listing of files, but trying to open the files creates an exception 'No such file or directory'. (Android 8.0, tested on several devices.)
//create a file in internal storage
FileOutputStream output = null;
output = openFileOutput("xxxyyy.txt", Context.MODE_PRIVATE);
String str = "Just any string";
byte[] bytes = str.getBytes();
output.write(bytes, 0, bytes.length);
output.close();
//list the files
String lst[] = fileList();
for (int i = 0; i < lst.length; i++)
{ Log.v("MM" , "INTERNAL FILES: "+lst[i]); }
//system reply: INTERNAL FILES: xxxyyy.txt, ......
//check if file exists and try to open it for reading
File file = new File("xxxyyy.txt");
Log.v("XX" , "TEST: file exists? " + file.exists());
//system reply: TEST: file exists? false
//try to open it for reading
FileInputStream input = null;
try {
input = new FileInputStream("xxxyyy.txt");
} catch (IOException e) {
Log.v("XX" , "TEST: " + e.getMessage());
}
//system reply: TEST: xxxyyy.txt (No such file or directory)
Many variations have been tried.
Any suggestion greatly appreciated!

If you need to access a file created with openFileOutput, you need to specify the correct directory when creating the File object, in this case:
File file = new File(getFilesDir(), "xxxyyy.txt");

Related

Create folder and store file in android 11

I'm working on an Android app that uses a SQLite database for storing survey data.
Problem: For Android version 10 and above devices,I can't store a backup copy of an SQLite database in some folder that won't be deleted even if app is uninstalled
For devices before Android version 10 it works fine with code below:
folder = Environment.getExternalStoragePublicDirectory("Db_Backup");// Folder Name
if (!folder.exists())
folder.mkdirs(); //Db_Backup folder gets created
For devices with Android version 11,it is not working
For android 10 and 11 devices, I have tried using code as below:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Files[] files=getExternalFilesDirs(Environment.DIRECTORY_DOWNLOADS);
folder=files[0];
// OR
folder = getFilesDir();
if (!folder.exists())
folder.mkdirs(); // Db_Backup folder is created in app directory
......
}
Above code creates a backup copy to android/data/com.example.packagename/files/backup/{filename.db} this location only
Issue: when app is uninstalled or app data gets cleared the .db backup file also gets removed or cleared
exportDatabaseNew() function that I am using is as below:
private void exportDatabaseNew(LinearLayout linearLayout) {
FileOutputStream output = null;
try {
File dbFile = getDatabasePath(DatabaseHelper.DATABASE_NAME);
FileInputStream fis = new FileInputStream(dbFile);
File[] files;
File folder = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
files=getExternalFilesDirs("Db_Backup");
folder=files[0];
Log.i("export", "exportDatabaseNew: " + folder.getAbsolutePath());
} else {
folder = Environment.getExternalStoragePublicDirectory("Db_Backup");//Folder Name
Log.i("export", "exportDatabaseNew: " + folder.getAbsolutePath());
}
if (!folder.exists())
folder.mkdirs();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
String currentDate = df.format(new Date());
String backupName = "Survey_" + currentDate + ".db";
File myFile = new File(folder, backupName);// Filename
output = new FileOutputStream(myFile);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
Snackbar.make(linearLayout, R.string.backup_complete, Snackbar.LENGTH_LONG)
.show();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Create your own folder in public Documents directory and write your file to that folder.
For Android 11, you have to either:
Save files in your application directory
Save files into public directories
If you really must, any other location that is NOT a different app directory, it requires the following permission:
< uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage"/>
This permission only applies for android 11 and above. Do note that if you want your app to be published on Google Play Store you'll need to provide a good reason why you want this permission and you are not willing to simply store it as part of your app's files.

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?

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)");

I need to be able to store sound files for my application on sdcard

I've read a lot of topics but none seem to cover what I need.
I basically have a load of sound files and I want to be able to play them in the application from the sdcard.
I also want to be able to install them there in the first place when the application is installed.
I am using Eclipse with the android SDK and currently my Target project is v1.6
Can anyone help?
Thanks
OK so I found the answer!
First we need to get the external Storage Directory to a variable called baseDir.
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
Then Create the directory mysounds on the SDcard
File folder = new File(Environment.getExternalStorageDirectory() + "/mysounds");
boolean success = false;
if(!folder.exists())
{
success = folder.mkdir();
}
if (!success)
{
// Do something on success
}
else
{
// Do something else on failure
}
Then This following bit of code will copy all the files with sound at the beginning of the name from the assets directory to the mysounds directory you have already created.
try {
AssetManager am = getAssets();
String[] list = am.list("");
for (String s:list) {
if (s.startsWith("sound")) {
Log.d("Notice", "Copying asset file " + s);
InputStream inStream = am.open(s);
int size = inStream.available();
byte[] buffer = new byte[size];
inStream.read(buffer);
inStream.close();
FileOutputStream fos = new FileOutputStream(baseDir + "/mysounds/" + s);
fos.write(buffer);
fos.close();
}
}
}
Hope this helps someone!

How to read file from phone's internal memory in 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");

Categories

Resources