I have a binary file in root of apk and I can check it by:
AssetManager assets = Context().getResources().getAssets();
assets.list("/")
It exists in returning list. But how can I open it?
Because when I try to open the file by using this code:
assets.open("/test.bin")
I faced by FileNotFoundException.
finally, I soloved it by using getClass().getResourceAsStream() instead of assetManager:
public byte[] loadBinAsset(String name) {
AssetManager assets = context.getResources().getAssets();
InputStream stream = null;
try {
try {
stream = assets.open(name);
} catch (IOException e) {
stream = context.getClass().getResourceAsStream("/" + name);
}
return readFully(stream);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
Related
I am trying to copy a file over to the root SD card on an Android device.
When I execute the code, it is going to the sdcard/Android/Data/<packageName>/files folder.
I have tried several different options without any success.
Also, I have checked the app to make sure it has write and read access to external memory.
private void copyfiles() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("ini");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null)
for (String filename: files) {
InputStream in = null;
OutputStream out = null;
try { in = assetManager.open("sdcard/" + filename);
//File outFile = new File(Environment.getExternalStorageDirectory(), filename);
File outFile = new File(getExternalFilesDir(null), filename);
if (!(outFile.exists())) { // File does not exist...
out = new FileOutputStream(outFile);
pastefiles( in , out);
}
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
} finally {
if ( in != null) {
try { in .close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
here is string to setDataSource
/data/data/com.player/app_player/file.mp3
getting E/Exception: setDataSource failed.
here is the code:
mediaPlayer.setDataSource(context, Uri.parse("/data/data/com.player/app_player/file.mp3"));
I stored that file using this code
getContext().getDir("player", Context.MODE_PRIVATE)
which is same as /data/data/com.player/app_player
using content://data/data/com.player/app_player/file.mp3 did not work.
This is how I solve it.
String musicUrl = "";
if (songSavedInDB()) {
musicUrl = "here is any file path(Internal or external)"
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(musicUrl);
mPlayer.setDataSource(fileInputStream.getFD());
fileInputStream.close();
mPlayer.prepare();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
musicUrl = "here is url";
try {
mPlayer.setDataSource(getContext(), Uri.parse(musicUrl));
mPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
i am trying to create a file in the internal storage, i followed the steps in android developers website but when i run the below code there is no file created
please let me know what i am missing in the code
code:
File file = new File(this.getFilesDir(), "myfile");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fOut = null;
try {
fOut = openFileOutput("myfile",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fOut.write("SSDD".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
By default these files are private and are accessed by only your application and get deleted , when user delete your application
For saving file:
public void writeToFile(String data) {
try {
FileOutputStream fou = openFileOutput("data.txt", MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fou);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
For loading file:
public String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("data.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Try to get the path for storing files were the app has been installed.The below snippet will give app folder location and add the required permission as well.
File dir = context.getExternalFilesDir(null)+"/"+"folder_name";
If you are handling files that are not intended for other apps to use, you should use a private storage directory on the external storage by calling getExternalFilesDir(). This method also takes a type argument to specify the type of subdirectory (such as DIRECTORY_MOVIES). If you don't need a specific media directory, pass null to receive the root directory of your app's private directory.
Probably, this would be the best practice.
Use this method to create folder
public static void appendLog(String text, String fileName) {
File sdCard=new File(Environment.getExternalStorageDirectory().getPath());
if(!sdCard.exists()){
sdCard.mkdirs();
}
File logFile = new File(sdCard, fileName + ".txt");
if (logFile.exists()) {
logFile.delete();
}
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.write(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this method, you have to pass your data string as a first parameter and file name which you want to create as second parameter.
I am trying firstly to download the file and its content from Dropbox in Android app using Dropbox Core API but when i execute the following code the app crushes.
EDIT: I have used two functions downloadDropboxFile and copy functions. The problem is that i am getting blank data when i read the local file which is supposed to contain the dropbox file data.
Here is the code where i call the function
downloadDropboxFile("/userandpass.txt");
if (mDBApi.getSession().isLinked())
{
InputStream instream = new FileInputStream(String.valueOf(getExternalCacheDir()) + "/userandpass.txt");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
mTestOutput.setText(buffreader.readLine());
}
Here is the functions
private boolean downloadDropboxFile(String fileSelected) {
File dir = new File(String.valueOf(getExternalCacheDir()));
if (!dir.exists())
dir.mkdirs();
try {
File localFile = new File(dir + fileSelected);
if (!localFile.exists()) {
localFile.createNewFile();
copy(fileSelected, localFile);
} else {
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
private void copy(final String dbPath, final File localFile) {
new Thread(new Runnable() {
#Override
public void run() {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
try {
DropboxAPI.DropboxInputStream fd = mDBApi.getFileStream(dbPath,null);
br = new BufferedInputStream(fd);
bw = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break;
}
bw.write(buffer, 0, read);
}
} catch (DropboxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}). start();
}
Dropbox Core API Implementation on Android Studio:
On app/libs i have the:
dropbox-android-sdk-1.6.3.jar
httpmime--4.0.3.jar
json_simple-1.1.jar
Your issue is here :
if (!localFile.exists()) {
localFile.createNewFile(); //otherwise dropbox client will fail silently
}
The exception is :
java.io.IOException: open failed: EROFS (Read-only file system)
This means you're trying to create a File on a location that is read only in the phone's memory, I'm guessing the internal storage. Have a look at this excellent answer by Mark Murphy on creating a File based on locations that can be written to.
Hoping this has been of some help, happy coding ;-)
I have to open a file that in the /res/raw/ folder, but it seems that android, doesn't recognize the path.
Here is my code:
public static void openRec()
{
//this is the wav file that I have to analyze
File file = new File("/res/raw/chirp.wav");
try {
FileInputStream in = new FileInputStream(file);
chirp = new byte[(int) file.length()];
in.read(chirp);
Log.d("xxx", "" + chirp.length);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT:
I have another method openRec in which, the path is passed as argument:
public static void openRec(String path) {
File file = new File(path);
try {
FileInputStream in = new FileInputStream(file);
recording = new byte[(int) file.length()];
in.read(recording);
Log.d("xxx", "" + recording.length);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I would a method that do the same thing but with the ffile in /res/raw. How do I that?
Use in this manner
public static void openRec()
{
//this is the wav file that I have to analyze
try {
InputStream in = getResources().openRawResource(R.raw.chirp);
chirp = new byte[(int) file.length()];
in.read(chirp);
Log.d("xxx", "" + chirp.length);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}