How to write to a file saved in project directory - android

I'm trying to write to a file at run time saved in project directory. But I'm getting below error:
java.io.FileNotFoundException: multidex.keep: open failed: EROFS (Read-only file system)
I'm I giving a wrong file path or I cannot edit the files at runtime? Please suggest. Below is my code:
private void saveInMultidexKeepFile(List externalDexClasses) {
if (externalDexClasses != null && externalDexClasses.size() > 0) {
File file = new File("multidex.keep");
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
OutputStreamWriter outWriter = new OutputStreamWriter(fOut);
for (int i = 0; i < externalDexClasses.size(); i++) {
outWriter.append(externalDexClasses.get(i).toString());
outWriter.append("\n");
LOGD("Multidex:", outWriter.toString());
}
outWriter.close();
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
LOGD("Multidex:", e.getMessage());
} catch (IOException e) {
e.printStackTrace();
LOGD("Multidex:", e.getMessage());
}
}
}

I think you simply cannot, why you want modify this file?

Related

Android Studio How to fix FileNotFoundException

I am trying to export some data on my app. Even though I set required permission on manifest and deleted build multiple times, it gives the same error. How can I fix it?
FileNotFoundException: /storage/emulated/0/VocAppFile/output.txt (No such file or directory)
The thing is there is no such folder like above in my phone. But /storage/emulated/0/ is the default directory.
My code is this:
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
File Root = Environment.getExternalStorageDirectory();
Log.d("Export to", Root.getAbsolutePath());
File Dir = new File(Root.getAbsolutePath()+"/AppFile");
if(!Dir.exists()){
Dir.mkdir();
}
File file = new File(Dir,"output.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
for(String[] d : data){
//data comes ready
fos.write(d[0].getBytes());
fos.write(d[1].getBytes());
}
fos.close();
Toast.makeText(getApplicationContext(), "Data exported",
Toast.LENGTH_SHORT).show();
}catch (FileNotFoundException e){
Log.wtf("My activity", "Error in exporting words");
e.printStackTrace();
}catch (IOException e){
Log.wtf("My activity", "Error in exporting words");
e.printStackTrace();
}
Put this line after File Dir = ...
New Line
file.createNewFile();
Final Code will be like this
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
File Root = Environment.getExternalStorageDirectory();
Log.d("Export to", Root.getAbsolutePath());
File Dir = new File(Root.getAbsolutePath()+"/AppFile");
if(!Dir.exists()){
Dir.mkdir();
}
File file = new File(Dir,"output.txt");
file.createNewFile();
try {
FileOutputStream fos = new FileOutputStream(file);
for(String[] d : data){
//data comes ready
fos.write(d[0].getBytes());
fos.write(d[1].getBytes());
}
fos.close();
Toast.makeText(getApplicationContext(), "Data exported",
Toast.LENGTH_SHORT).show();
}catch (FileNotFoundException e){
Log.wtf("My activity", "Error in exporting words");
e.printStackTrace();
}catch (IOException e){
Log.wtf("My activity", "Error in exporting words");
e.printStackTrace();
}
I fixed the problem with following steps 1-2-4 of stackoverflow.com/a/41221852/5488468

Android: Failed to read Data Meta Data

I have dat file, which is binary file.It currently inside raw folder on my project.
I want to use the file in my program.
I want to copy it to certain location on the device but when executing the method, I am getting the error "Failed to read Data Meta Data"
Here is the method:
public void copyRawOnSdCard(){
File sdcard = Environment.getExternalStorageDirectory();
String targetPath = sdcard.getAbsolutePath() + File.separator + "shape_predictor_68_face_landmarks.dat";
File file = new File(targetPath);
if (!file.exists())
{
final ProgressDialog pd; pd = ProgressDialog.show(this, "Copy Files for the First Time", "Please wait",
true);
pd.show();
InputStream in = getResources().openRawResource(
getResources().getIdentifier("shape_predictor_68_face_landmarks",
"raw", getPackageName()));
FileOutputStream out = null;
try {
out = new FileOutputStream(targetPath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
in.close();
}catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
pd.cancel();
}
}
Ideas?
Thanks
Apparently There is another implementation solution and that is to put it the .dat binary file in assets folder.
And here is the implementation:
https://stackoverflow.com/questions/4447477/how-to-copy-files-from-assets-folder-to-sdcard
And it worked for me.

Failing to store bitmap as a file

Im trying to save a bitmap as a file however its failing for some reason
Thats the error I keep getting, it only pops up on 5.0 however I tested it on 6.0 sdk and its working fine
java.io.FileNotFoundException: /storage/sdcard/Pictures/mFile/image1491238127.jpg: open failed: EISDIR (Is a directory)
private File saveBitmap(Bitmap bitmap, String path) {
File file = null;
if (bitmap != null) {
file = new File(path);
file.mkdirs();
try {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(path);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
try {
return Compressor.getDefault(getContext()).compressToFile(file);
}catch (Exception e){
return file;
}
}
private File saveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "Image-Fashom" +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
As I observe on your code I found you creating file.mkdir(); it means you creating a new file not get u need to write the code after try catch return exception.
try {
//it gets file path
file = new File(path);
return Compressor.getDefault(getContext()).compressToFile(file);
}catch (Exception e){
return file;
}
ting the exist file..

Can't create file in the internal storage

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.

Writing to text file in "APPEND mode" in emulator-mode,

In my Android app I should store the data from user in simple text-file, that I created in the raw directory. After this, I'm trying to write file in APPEND MODE by using simple code from the Google's examples:
try
{
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_APPEND);
fos.write((nameArticle+"|"+indexArticle).getBytes());
fos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
But nothing happens: no exceptions, but I can see nothing in my FILE_NAME, besides the single record, which was added by me.
What am I doing wrong ? Is it possible at common to write to file in emulator ?
openFileOutput will only allow you to open a private file associated with this Context's application package for writing. I'm not sure where the file you're trying to write to is located. I mean full path. You can use the code below to write to a file located anywhere (as long as you have perms). The example is using the external storage, but you should be able to modify it to write anywhere:
public Uri writeToExternalStoragePublic() {
final String filename = mToolbar.GetTitle() + ".html";
final String packageName = this.getPackageName();
final String folderpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + packageName + "/files/";
File folder = new File(folderpath);
File file = null;
FileOutputStream fOut = null;
try {
try {
if (folder != null) {
boolean exists = folder.exists();
if (!exists)
folder.mkdirs();
file = new File(folder.toString(), filename);
if (file != null) {
fOut = new FileOutputStream(file, false);
if (fOut != null) {
fOut.write(mCurrentReportHtml.getBytes());
}
}
}
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
return Uri.fromFile(file);
} finally {
if (fOut != null) {
try {
fOut.flush();
fOut.close();
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
In the example you have given, try catching 'I0Exception`, I have a feeling you do not have permission where you are trying to write.
Have a Happy New Year.

Categories

Resources