FileNotFoundException while reading an uploaded file - android

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?

Related

My app can't open internal storage file

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

Why does AssetManager list() not show my assets folder?

In my Android app I have packaged a file in the /assets folder that needs to be copied to the SDCARD. When I list the contents of the assets folder to a String[] I get "images", "sounds", "webkit" and "kioskmode" but not my file manually added to the assets folder.
My code is here:
private void copyAsset () {
AssetManager am = getApplicationContext().getAssets();
String[] files = null;
try {
files = am.list("");
} catch (IOException e) {
}
for (String filename : files) {
if (filename.equals("images") || filename.equals("kioskmode") ||
filename.equals("sounds") || filename.equals("webkit")) {
Log.i(TAG, "Skipping folder " + filename);
continue;
}
InputStream in = null;
OutputStream out = null;
try {
in = am.open(filename);
File outFile = new File(Environment.getExternalStorageDirectory().getPath(), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Error copying asset ", e);
}
}
}
Does it make a difference that this is a second class in my app and is called in my MainActivity using Intent showHelper = new Intent(this, HelperManager.class);
startActivity(showHelper); ?
I have tried the 2nd line (AssetManager am = ...) with and without the getApplicationContext() bit, tried moving the file into a subfolder of /assets and tried files = am.list("") with leading and trailing slashes. If I use a subfolder the files array is empty when the code runs (set a breakpoint on the files = am.list(""); line and inspected it at run time.
The strange thing is that it worked once - when I first wrote the code, but for further testing, I deleted the file from the /sdcard folder on the phone, and it never worked since even though the file is still in the assets folder.
I am using Android Studio if that matters.
Thanks
Managed to get a solution using Load a simple text file in Android Studio as a fix. It still puts the 4 folders in the files array but I Can skip them using code as given above, although I should rather check for the file I want rather than the 4 I don't!

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