Can't read file from android internal storage into byte array - android

I am trying to save a p12 file to internal storage like so:
File file = new File(mContext.getFilesDir(), "fileName.p12");
I then proceed to read this file into a byte array like so:
byte[] bFile = new byte[(int) file.length()];
try {
bFile = org.apache.commons.io.FileUtils.readFileToByteArray(file);
}catch(Exception e){
e.printStackTrace();
}
After doing this, I get a FileNotFoundException even though the debugger shows that the file is saved in /data/data/com.fm.sg.android/files/fileName.p12
What am I doing wrong?

path = context.getFilesDir().getAbsolutePath().toString();
String filename = "fileName.p12";
File file = new File(path,filename);
then the rest of your code....this should make it...

Related

How can I get file path on raw resources in Android Studio?

I have been using this tutorial to make some face detections on picture. The problem is when I getting the file path that used on java
String xmlFile = "E:/OpenCV/facedetect/lbpcascade_frontalface.xml";
CascadeClassifier classifier = new CascadeClassifier(xmlFile);
How can I translate on android studio. I try put my lbpcascade_frontalface.xml on raw resources. CascadeClassifier is a class that opencv library provided. The only problem is they only loaded string path (on xmlfile).
this is my code.
String pathtoRes = getRawPathAtempt2(context);
CascadeClassifier cascadeClassifier = new CascadeClassifier();
cascadeClassifier.load(pathtoRes);
I translated to some method like this.
public String getRawPathAtempt2(Context context) {
return "android.resource://" + context.getPackageName() + "/raw/" + "lbpcascade_frontalface.xml";
}
I get the asertions error by opencv that tell me the file is null. Thats mean I had been wrong when I used file path on my method. how can I get file path on raw resources? help me please I have been stuck for several days now
how can i get file path on raw resources?
You can't. There is no path. It is a file on your development machine. It is not a file on the device. Instead, it is an entry in the APK file that is your app on the device.
If your library supports an InputStream instead of a filesystem path, getResources().openRawResource() on a Context to get an InputStream on your raw resource.
This is how i solved the problem with #CommonWare Answer
i'm using input stream to get file
is = context.getResources().openRawResource(R.raw.lbpcascade_frontalface);
so make the file will be opened and i will make a point to the File class
File cascadeDir = context.getDir("cascade", Context.MODE_PRIVATE);
mCascadeFile = new File(cascadeDir, "lbpcascade_frontalface.xml");
and then i make a search to the path file using getAbsolutePath like this
cascadeClassifier.load(mCascadeFile.getAbsolutePath());
take a look at my full code
try {
is = context.getResources().openRawResource(R.raw.lbpcascade_frontalface);
File cascadeDir = context.getDir("cascade", Context.MODE_PRIVATE);
mCascadeFile = new File(cascadeDir, "lbpcascade_frontalface.xml");
os = new FileOutputStream(mCascadeFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
is.close();
os.close();
cascadeClassifier.load(mCascadeFile.getAbsolutePath());
} catch (IOException e) {
Log.i(TAG, "face cascade not found");
}
Uri video = Uri.parse("android.resource://com.test.test/raw/filename");
Using this you can access the file in raw folder, if you want to access the file in asset folder use this URL...
file:///android_asset/filename
Make sure you don't add the extension to the filename. E.g. "/movie" not "/movie.mp4".
Refer to this link:
Raw folder url path?
We can use this Alternative method for finding the path of Files in Raw Folder.
InputStream inputStreamdat=getResources().openRawResource(R.raw.face_landmark_model);
File model=getDir("model", Context.MODE_PRIVATE);
File modelFile=new
File(model,"face_landmark_model.dat");
FileOutputStream os1 = new
FileOutputStream(modelFile);
byte[] buffer1 = new byte[4096];
int bytesRead1;
while ((bytesRead1=inputStreamdat.read(buffer1))!=-1) {
os1.write(buffer1, 0, bytesRead1);
}
inputStreamdat.close();
os1.close();
You Can Use
modelFile.getAbsolutePath()); For getting the Path

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?

How can I read json file from SD Card

I need to read a json file from the SD card and display the data in the spinner. Is there any way to read the data from file in Android and display the contents of that file in spinner?
First read the file from SD card and then parse that file
Step-1
Retrieve the data from file from SD card. see tutorial
Step-2
Parse the data. See How to parse JSON String
Sample code
try {
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
FileInputStream stream = new FileInputStream(yourFile);
String jString = null;
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
/* Instead of using default, pass in a decoder. */
jString = Charset.defaultCharset().decode(bb).toString();
}
finally {
stream.close();
}
JSONObject jObject = new JSONObject(jString);
} catch (Exception e) {e.printStackTrace();}

manually read a file in the files directory

Friends, My application has to get current gps position in every seconds and write this data as byte array to a file in files directory. To check the data in that file I tried to open mnually. But i couldn't open. How can i read the file. The file is a text file
private static String readFileAsString(String file) throws IOException {
byte[] bytes = new byte[(int) new File(file).length()];
BufferedInputStream stream = new BufferedInputStream(new FileInputStream(file));
stream.read(bytes);
return new String(bytes);
}

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