I am trying to read a CSV file, load its content to a spinner. I have given relevant permissions MANAGE_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE to read a file from external storage. I have placed the CSV file in a directory requested permission on runtime. Also the file.exists() function return true but still unable to read csv file. Where am I going wrong?
Here is the error log:
022-02-27 18:03:32.457 13080-13080/com.example.locationfetcher_v2 W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Khidmah/input.csv: open failed: EACCES (Permission denied)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at libcore.io.IoBridge.open(IoBridge.java:492)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:160)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:115)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at java.io.FileReader.<init>(FileReader.java:58)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at com.example.locationfetcher_v2.MainActivity.onCreate(MainActivity.java:157)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.Activity.performCreate(Activity.java:8157)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.Activity.performCreate(Activity.java:8129)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1310)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3494)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3693)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2135)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.os.Handler.dispatchMessage(Handler.java:106)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.os.Looper.loop(Looper.java:236)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.ActivityThread.main(ActivityThread.java:8059)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at java.lang.reflect.Method.invoke(Native Method)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at libcore.io.Linux.open(Native Method)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7932)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at libcore.io.IoBridge.open(IoBridge.java:478)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: ... 19 more
Below is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Using Dexter Library
Dexter.withContext(this)
.withPermissions(
Manifest.permission.MANAGE_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.CAMERA
).withListener(new MultiplePermissionsListener() {
#Override public void onPermissionsChecked(MultiplePermissionsReport report) {/* ... */}
#Override public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {/* ... */}
}).check();
MultiplePermissionsListener dialogMultiplePermissionsListener =
DialogOnAnyDeniedMultiplePermissionsListener.Builder
.withContext(this)
.withTitle("Camera, Storage and Location permission")
.withMessage("All Camera, Storage and Location permission are required for this application")
.withButtonText(android.R.string.ok)
.build();
//// Read data from CSV file
List<String> addresses = new ArrayList<String>();
Spinner address_spinner = findViewById(R.id.spinnerAddress);
// File file = new File(Environment.getExternalStorageDirectory() + "/Khidmah/", "input.csv");
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "input.csv");
show_notification(file.getPath());
show_notification(new Boolean(file.exists()).toString());
FileInputStream fis = null;
try {
if (file.exists()){
show_notification("can read - " + new Boolean(file.canRead()).toString());
CSVReader reader = new CSVReader(new FileReader(file.toURI().toString()));
show_notification("successfully read file...");
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
// System.out.println(nextLine[0] + nextLine[1] + nextLine[2]);
addresses.add(nextLine[0] + nextLine[1] + nextLine[2]);
show_notification(nextLine[0] + nextLine[1] + nextLine[2]);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item,addresses);
address_spinner.setAdapter(adapter);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (CsvValidationException e) {
e.printStackTrace();
}
}
Here is AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.locationfetcher_v2">
<!-- Always include this permission -->
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- Include only if your app benefits from precise location access. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.LocationFetcher_v2"
android:foregroundServiceType="location">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
</application>
</manifest>
UPDATE
I am now using Dexter Library to grant permissions. I have added additional permission MANAGE_EXTERNAL_STORAGE and place the input.csv file in Public Directory i.e. Downloads folder. However now it's giving following error:
open failed: ENOENT (No such file or directory)
After File.exists() use File.canRead() before you act on the file.
This csv file is not created by your app.
Hence on Android 11 you are not the owner and although your app can check if the file exists it discovers with File.canRead() that the file is not accessable.
With MANAGE_EXTERNAL_STORAGE and the right runtime code your app can obtain access.
The right code would start an intent for Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION.
Related
I have two different memory locations in android. One is the internal memory location called the external sd card and the other one is the removable memory card.
I have got the read and write permissions in the manifest.
I am also checking its availability.
I have also added android:requestLegacyExternalStorage="true"
My problem is that I am not able to write to this removable media. When I try to write I get this error.
2020-06-06 20:54:13.334 29148-29148/com.test.debug I/OMD::SDCard: /storage/8E14-3919 is removable external storage
2020-06-06 20:54:13.332 29148-29148/com.test.debug W/sdatabase.debug: type=1400 audit(0.0:8919357): avc: granted { read open } for pid=29148 path="/mnt/media_rw/8E14-3919" dev="mmcblk1p1" ino=1 scontext=u:r:untrusted_app:s0:c74,c258,c512,c768 tcontext=u:object_r:vfat:s0 tclass=dir
2020-06-06 20:54:13.336 29148-29148/com.test.debug W/System.err: java.io.FileNotFoundException: /storage/8E14-3919/freebookslibrary.db: open failed: EACCES (Permission denied)
2020-06-06 20:54:13.336 29148-29148/com.test.debug W/System.err: at libcore.io.IoBridge.open(IoBridge.java:496)
2020-06-06 20:54:13.336 29148-29148/com.test.debug W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:235)
2020-06-06 20:54:13.336 29148-29148/com.test.debug W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:125)
2020-06-06 20:54:13.337 29148-29148/com.test.debug W/System.err: at com.khan.mybookslibrary.BackUpExternal.exportDatabase(BackUpExternal.java:145)
2020-06-06 20:54:13.337 29148-29148/com.test.debug W/System.err: at com.khan.mybookslibrary.BackUpExternal.access$100(BackUpExternal.java:57)
2020-06-06 20:54:13.337 29148-29148/com.test.debug W/System.err: at com.khan.mybookslibrary.BackUpExternal$4.onClick(BackUpExternal.java:115)
2020-06-06 20:54:13.337 29148-29148/com.test.debug W/System.err: at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:177)
2020-06-06 20:54:13.337 29148-29148/com.test.debug W/System.err: at android.os.Handler.dispatchMessage(Handler.java:107)
2020-06-06 20:54:13.337 29148-29148/com.test.debug W/System.err: at android.os.Looper.loop(Looper.java:213)
2020-06-06 20:54:13.337 29148-29148/com.test.debug W/System.err: at android.app.ActivityThread.main(ActivityThread.java:8147)
2020-06-06 20:54:13.337 29148-29148/com.test.debug W/System.err: at java.lang.reflect.Method.invoke(Native Method)
2020-06-06 20:54:13.337 29148-29148/com.test.debug W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
2020-06-06 20:54:13.337 29148-29148/com.test.debug W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
2020-06-06 20:54:13.338 29148-29148/com.test.debug W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
2020-06-06 20:54:13.338 29148-29148/com.test.debug W/System.err: at libcore.io.Linux.open(Native Method)
2020-06-06 20:54:13.338 29148-29148/com.test.debug W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
2020-06-06 20:54:13.338 29148-29148/com.test.debug W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:252)
2020-06-06 20:54:13.338 29148-29148/com.test.debug W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
2020-06-06 20:54:13.338 29148-29148/com.test.debug W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:8015)
2020-06-06 20:54:13.338 29148-29148/com.test.debug W/System.err: at libcore.io.IoBridge.open(IoBridge.java:482)
2020-06-06 20:54:13.338 29148-29148/com.test.debug W/System.err: ... 12 more
2020-06-06 20:54:13.406 29148-29212/com.test.debug W/libEGL: EGLNativeWindowType 0x6f62540b90 disconnect failed
> The code with which am trying to achieve is as follows:
private void exportDatabase(String fileName) {
final File dbFile = context.getDatabasePath(DATABASE_NAME);//existing database file path
SDCard sdc = new SDCard();
File file = sdc.findSdCardPath(context);
FileChannel source = null;
FileChannel destination = null;
if(file!= null){
String backUpPath = file.getAbsolutePath() + "/" + fileName + ".db";
try {
source = new FileInputStream(dbFile).getChannel();
destination = new FileOutputStream(backUpPath).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
alert(context.getResources().getString(R.string.Database_exported_external));
} catch (IOException e) {
e.printStackTrace();
alert(context.getResources().getString(R.string.Failed_export_database_external));
}
}
else
return;
}
I need a solution to this problem
I am trying to create a image file to external storage to share it. but while trying following code I am having some error
var icon: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.namelogo)
val shareIntent = Intent(Intent.ACTION_SEND)
shareIntent.type = "image/*"
val bytes = ByteArrayOutputStream()
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
val path = File.separator + "temporary_file.jpg"
val f = File(Environment.getExternalStorageDirectory().toString(), path)
try {
if (!f.parentFile.exists())
f.parentFile.mkdirs()
if (!f.exists())
f.createNewFile()
f.createNewFile()
val fo = FileOutputStream(f)
fo.write(bytes.toByteArray())
} catch (e: IOException) {
Log.e("path = ", "+ $path " + e.toString())
e.printStackTrace()
}
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/IronyBalls/temporary_file.jpg"));
startActivity(Intent.createChooser(shareIntent, "Share Image"))
Till now I found solutions only to use
if (!f.parentFile.exists())
f.parentFile.mkdirs()
if (!f.exists())
f.createNewFile()
and
to set permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
that I have already used.But still gettig error as below
in Error Tab
E/path =: + /temporary_file.jpg java.io.IOException: Permission denied
and in info tab
W/System.err: java.io.IOException: Permission denied
W/System.err: at
java.io.UnixFileSystem.createFileExclusively0(Native Method)
W/System.err: at
java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
W/System.err: at java.io.File.createNewFile(File.java:948)
W/System.err: at
com.irony.balls.MainActivity$onCreate$8.onClick(MainActivity.kt:277)
W/System.err: at android.view.View.performClick(View.java:5611)
10-15 20:33:17.912 29759-29759/com.irony.balls
W/System.err: at
android.view.View$PerformClick.run(View.java:22276) 10-15 20:33:17.912
29759-29759/com.irony.balls
W/System.err: at
android.os.Handler.handleCallback(Handler.java:751) 10-15 20:33:17.912
29759-29759/com.irony.balls
W/System.err: at
android.os.Handler.dispatchMessage(Handler.java:95) 10-15 20:33:17.912
29759-29759/com.irony.balls
W/System.err: at
android.os.Looper.loop(Looper.java:154) 10-15 20:33:17.912
29759-29759/com.irony.balls W/System.err: at
android.app.ActivityThread.main(ActivityThread.java:6195) 10-15
20:33:17.912 29759-29759/com.irony.balls W/System.err: at
java.lang.reflect.Method.invoke(Native Method) 10-15 20:33:17.912
29759-29759/com.irony.balls W/System.err: at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:874)
10-15 20:33:17.912 29759-29759/com.irony.balls W/System.err: at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:764)
If your device is working on Android 6 or higher have you already requested runtime permissions?
See https://developer.android.com/training/permissions/requesting.html for more details.
I need to help for mkdir failed: EACCES (Permission denied)
My build setting;
minSdkVersion 15 - targetSdkVersion 19 - compileSdkVersion 25 -
buildToolsVersion "25.0.0"
I use Android Studio 2.3
Debug Device : Samsung J1 (SM-J200F) Android 5.1.1 Android Security Patch Level 2016-12-01
and
Sony Xperia Z5 (E6603) Android 7.0 Android Security Patch Level 2016-12-01
But Google Play APK version is working
Android Manifest;
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Debug Log;
Line 124 : `FileOutputStream out = new FileOutputStream(file);`
`03-23 10:59:06.096 24568-24788/com.myAppName I/System.out: AsyncTask #1 calls detatch()
03-23 10:59:06.106 24568-24568/com.myAppName W/System.err: mkdir failed: EACCES (Permission denied) : /storage/emulated/0/MyAppName
03-23 10:59:06.106 24568-24568/com.myAppName D/Failed: Open
03-23 10:59:06.106 24568-24568/com.myAppName W/System.err: java.io.FileNotFoundException: /storage/emulated/0/MyAppName/MyAppName-6662.jpg: open failed: ENOENT (No such file or directory)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at libcore.io.IoBridge.open(IoBridge.java:456)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:72)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at com.myAppName.helper.FileDownloadHelper.SaveImage(FileDownloadHelper.java:124)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at com.myAppName.helper.FileDownloadHelper.onPostExecute(FileDownloadHelper.java:59)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at com.myAppName.helper.FileDownloadHelper.onPostExecute(FileDownloadHelper.java:27)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at android.os.AsyncTask.finish(AsyncTask.java:636)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at android.os.AsyncTask.access$500(AsyncTask.java:177)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at android.os.Looper.loop(Looper.java:145)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6946)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at java.lang.reflect.Method.invoke(Native Method)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at libcore.io.Posix.open(Native Method)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: at libcore.io.IoBridge.open(IoBridge.java:442)
03-23 10:59:06.111 24568-24568/com.myAppName W/System.err: ... 15 more`
My save function;
private Bitmap SaveImage(Bitmap result) {
String filename = "";
File instaFolder = new File(Environment.getExternalStorageDirectory().toString()
+ "/" + Constants.FOLDER_NAME);
if (!instaFolder.exists())
instaFolder.mkdir();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
filename = Constants.FOLDER_NAME + "-" + n + ".jpg";
file = new File(instaFolder, filename);
if (file.exists()) file.delete();
_mImageUrl = file.getPath();
try {
FileOutputStream out = new FileOutputStream(file);
result.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Try this:
check if mkdir() returns success or not..and remove .toString()
File folder = new File(Environment.getExternalStorageDirectory() + "/" + Constants.FOLDER_NAME);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
Log.d("Success","Open");
// Do work on success
} else {
Log.d("Failed","Open");
// Do work else on failure
}
I want to use a pre fill database in my app so I found this code.
DB_NAME = "urg1718.sqlite"
public SQLiteDatabase openDatabase() {
File dbFile = context.getDatabasePath(DB_NAME);
String path = dbFile.getAbsolutePath();
Log.i("path", "openDatabase: " + path);
if (!dbFile.exists()) {
try {
//the file doesn't exist yet so this function is called
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
//check if the database is present in the folder
Log.i("database", "openDatabase: " + dbFile.exists());
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
}
private void copyDatabase(File dbFile) throws IOException {
//pre fil database
InputStream is = context.getAssets().open(DB_NAME);
try {
//where the error occurs
OutputStream os = new FileOutputStream(dbFile);
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
os.flush();
os.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();;
} catch (IOException e) {
e.printStackTrace();
}
}
The "OutputStream os = new FileOutputStream" catch the following error.
java.io.FileNotFoundException: /data/data/jle.urgdegarde17_18/databases/urg1718: open failed: ENOENT (No such file or directory)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:456)
W/System.err: at java.io.FileOutputStream.(FileOutputStream.java:87)
W/System.err: at java.io.FileOutputStream.(FileOutputStream.java:127)
W/System.err: at java.io.FileOutputStream.(FileOutputStream.java:116)
W/System.err: at jle.urgdegarde17_18.AssetDatabaseOpenHelper.copyDatabase(AssetDatabaseOpenHelper.java:49)
W/System.err: at jle.urgdegarde17_18.AssetDatabaseOpenHelper.openDatabase(AssetDatabaseOpenHelper.java:35)
W/System.err: at jle.urgdegarde17_18.Chargement.isStoragePermissionGranted(Chargement.java:40)
W/System.err: at jle.urgdegarde17_18.Chargement.onCreate(Chargement.java:18)
W/System.err: at android.app.Activity.performCreate(Activity.java:5990)
W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
W/System.err: at android.app.ActivityThread.access$800(ActivityThread.java:151)
W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err: at android.os.Looper.loop(Looper.java:135)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5254)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
W/System.err: at libcore.io.Posix.open(Native Method)
W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:442)
W/System.err: ... 20 more
I tried to use getDatabasePath(), getDatabasePath().getAbsolutePath() and directly put the string returned by those functions into FileOutputStream
I also tried to remove the ".sqlite" from the database name.
I don't understand what i'm doing wrong ...
Thank's.
I'm trying to create a file in the external storage directory of the Nougat emulator. using the following code:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test987689");
if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
Toast.makeText(this, "External SD card not mounted", Toast.LENGTH_LONG).show();
}try {
if (file.getParentFile().exists() || file.getParentFile().mkdirs()) {
file.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
Permissons:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And I'm getting the following error:
W/System.err: java.io.IOException: Permission denied
W/System.err: at java.io.UnixFileSystem.createFileExclusively0(Native Method)
W/System.err: at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
W/System.err: at java.io.File.createNewFile(File.java:958)
W/System.err: at com.vibhinna.sreni.SplashActivity.onCreate(SplashActivity.java:41)
W/System.err: at android.app.Activity.performCreate(Activity.java:6658)
W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2584)
W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2692)
W/System.err: at android.app.ActivityThread.-wrap12(ActivityThread.java)
W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1445)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err: at android.os.Looper.loop(Looper.java:154)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6044)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
What am I doing wrong?
If your targetSdk is 23 or higher, you should request permissions dynamically.
to know more : Requesting Permissions at Run Time
to get File path you can use Context.getExternalFilesDir()/Context.getExternalCacheDir()
for example
String path=Context.getExternalCacheDir()+"file.text";
File file=new File(path)
it doesnt need permission if the filepath is "Android/data/app package/file name"