Sometimes I get Exception.java.io.FileNotFoundException, file open failed: EROFS ( Read- only file System) . I have WRITE_EXTERNAL_STORAGE permission in my manifest, once in a while when I have my services running then I get these exceptions and few operations will not be succeeded but if I reboot my device then it works fine.
I want to catch "Exception.java.io.FileNotFoundException" exception and reboot my device programmatically. My device is rooted one so I programmatically execute "su -c reboot".
I need to know how to catch " File open failed: EROFS " exception and trigger a reboot ??
Will solve your problem this:
try{
do whatever
}catch(FileNotFoundException ex){
if("EROFS ( Read- only file System)".equals(ex.getMessage())){
call code for reboot
}
}
You can replace the error message or even skip it
Edit: - based on comment
try{
do whatever
}catch(IOException ex){
if((ex instanceof FileNotFoundException) && "EROFS ( Read- only file System)".equals(ex.getMessage())){
call code for reboot
}
}
Related
I have created a file using
` try {
File myFile = new File("myfile");
if (myFile.exists())
myFile.delete();
outputStream = openFileOutput("myfile", Context.MODE_PRIVATE);
Log.d("MyServiceActivity", "file written");
outputStream.write(User.getInstance().getUserId().getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
`
How do i view the file created manually. Thanks in advance
Since the file is saved with Context.MODE_PRIVATE it is into internal memory, if you dont have root you will be not able to see this file with your phone
The best aproach to view your file is to open device monitor or Android monitor that is place in your Android Studio IDE
Note: run your app in debug mode to be able to see internal memory
directories and files !
Be sure to have your device pluged to your pc to run it
Happy coding
I'm working on a testcase for my application that should verify the correctness of an file import action. To automatically test this, my plan is to copy a file from my test assets directory into the downloads folder of the device under test and perform the import action using an Espresso test case.
Does somebody have experience with this? I'm running into the issue that my test case has no permission to write anything to the device.
So far I have created a dedicated manifest.xml file for my test application containing the required permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Furthermore, I'm performing this action before my test starts to grant the needed permission to the test case:
adb shell pm grant com.my_app_pacakge.test android.permission.WRITE_EXTERNAL_STORAGE
Unfortunately, when I create the file in the downloads directory the following exception is thrown at the moment I try to write contents to the backup file:
Caused by: java.io.FileNotFoundException: /storage/emulated/0/Download/small_backup: open failed: EACCES (Permission denied)
The relevant code is the following:
public void putBackupFile(String name ){
File backupFile = new File(Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DOWNLOADS ).getPath(), name );
try {
InputStream is = InstrumentationRegistry.getInstrumentation().getContext().getAssets().open( name );
FileOutputStream fileOutputStream = new FileOutputStream(backupFile);
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.close();
is.close();
} catch (IOException e1) {
throw new RuntimeException(e1);
}
}
The exception is triggered at: FileOutputStream fileOutputStream = new FileOutputStream(backupFile);
Answering to the original question: If you grant android.permission.WRITE_EXTERNAL_STORAGE from adb, you have to grant android.permission.READ_EXTERNAL_STORAGE as well:
adb shell pm grant com.my_app_pacakge.test android.permission.READ_EXTERNAL_STORAGE
It seems to be that if one ask for WRITE permission in an app, the READ permission is asked/granted automatically. If one does it from adb, the READ permission have to be granted additionally.
I realized that the appraoch states in my question was not the best approach: I have solved this in another way: transferring the required files using the adb command line:
adb push small_backup /mnt/sdcard/Download
This statement is integrated in my test setup (executed before running the test). In the test case I take for granted that the required files are available.
I'm currently trying to natively call on an executable on the shell from my Android Project which is in my application home directory. I can see via the command line when using ADB that my file is not getting executable file permissions, however. I've tried the following:
File file = new File(myFileLocation);
if(file.exists()){
boolean executable = file.setExecutable(true);
}
'executable' remains false.
I've also tried the following:
Process processChmod = Runtime.getRuntime().exec("/system/bin/chmod u+x " + myExecutableLocation);
processChmod.waitFor();
When I try to issue a command on the process, I get the following IOException:
java.io.IOException: Permission denied java.io.IOException: Error
running exec(). Command: [/storage/emulated/0/myApp/iperf, -c,
iperf.eltel.net] Working Directory: null Environment: null
The command I'm trying to issue is:
Runtime.getRuntime().exec("/storage/emulated/0/myApp/iperf -c iperf.eltel.net")
Again, at this stage, I can see that the file permissions on the process I wish to use is simply r/w and not executable. Any help appreciated! By the way, I'm trying to use the 'iPerf' C library and there is a compiled armeabi module as well as the original sources/JNI code. There are no compilation issues and this looks like a file permissions issue more than anything.
Files located on SD card aren't executable. Move the file to internal storage (e.g. to /data/local or, if you get permission denied, to data/local/tmp).
That is how I did it :
String filePath = getFilesDir().getAbsolutePath() + File.separator + "myFileName";
File myFile = new File(filePath);
if (!myFile.canExecute()) {
Log.d("File is not executable, trying to make it executable ...");
if (myFile .setExecutable(true)) {
Log.d("File is executable");
} else {
Log.d("Failed to make the File executable");
}
} else {
Log.d("File is executable");
}
I think Android's chmod does not understand u+x syntax, try using the numeric notation like 744.
The scenario I am going for is as follows:
Android application (apk) that is "generic", i.e. I do not want to recompile with different resources
APK will be "pre-installed" on devices and so will not be a "market" app
The application needs a custom configuration file that customizes it with text, etc. that can be different for each installation. (config file needs to be in same location with same name)
On app start-up the config file gets read and configures app according to the data in the config file
In essence, this would be a way to provision the application so that it takes on a specific look and feel based on the config file without having to recompile. Be able to load custom image files, text data, etc.
The problem is that the config file needs to be easily updated and "copied" to a non-rooted device without a SD card. So I need access to the a non-app specific location that is easily accessible via a USB connection and that the APK has access to at run-time. It seems that SharedPreferences and Android file IO is limited to the private app directory under /data/data/pkg/... or external storage. Any ideas would be greatly appreciated. Thanks.
Just thought I would update with at least a partial answer. At least some of my issue has to do with testing in debug mode on my Razr Maxx. When I am connected via USB debugging then the call to create a new file fails as follows:
06-06 10:04:30.512: W/System.err(2583): java.io.IOException: open failed: EACCES (Permission denied)
06-06 10:04:30.512: W/System.err(2583): at java.io.File.createNewFile(File.java:940)
When I am running the app standalone on my device or in an emulator then it all works as expected. Not sure if this is related specifically to Razr Maxx or some other issue?
My code that is working is (from: Write a file in external storage in Android) :
private void writeToSDFile(){
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data- storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
mStatusTV.append("\nExternal file system root: "+root);
// See https://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
file.createNewFile();
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Hi , How are you");
pw.println("Hello");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
mStatusTV.append("Write File 1: " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
mStatusTV.append("Write File 2: " + e.getMessage());
}
mStatusTV.append("\n\nFile written to "+file);
}
We have a USB port in our android tablet(version 4.0.3).
Pendrive File Systems Format are
NTFS
FAT32
When Pendrive File Systems Format are FAT32 File has been created Successfully. But When File Systems Format are NTFS, I got the Error Message as open failed: EACCESS (Permission denied).
I Need to create a New File from in the USB Pendrive. I have tried my sample code is
Button createFile = (Button) findViewById(R.id.createFile);
createFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try
{
File root = new File("/mnt/usbhost1");
Runtime.getRuntime().exec("chmod 777 " + root.getAbsolutePath());
File myFile = new File(root,"createNew.txt");
myFile.createNewFile();
Toast.makeText(getBaseContext(), "Done Creating File", Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
Here /usbhost1 is a Android tablet USB Path. Where I am mistaken. How to create a New File from in the NTFS File Systems Format.
Thanks in advance.
Regards
Bala
What you need is a way to enable support for NTFS in the kernel on your device. This could be achieved dynamically by building the ntfs-driver as loadable module (.ko file). This would need to be done for the specific version of the kernel that is running on your device.
Next you need a way to automatically load the module each time the systems restarts. this is also "do-able" in Android. You might want to try this app which does precisely that. i.e. load one or more kernel module(s) located anywhere on the Android device.
After this whenever one inserts a external-device(usb-drive) that has ntfs partitions, the kernel will be able to properly recognise and mount it. Hence apps can then access it at its proper location like "/mnt/usbhost1" etc.