I am making a app that store files get files from Internal Storage and lock those files in app directory /data/data/[package_name]/videos/.
I try to move files files through this method but it is not working for me.
source.renameTo(new File("data/data/" + this.getPackageName() + "/files/videos/" + video_title));
TRIED BEFORE
I tried this
source.renameTo(new File("/storage/emulated/0/" + this.getPackageName() + video_title));. This worked and move file from soure to /storage/emulated/0/.
I also checked this directory exisits.
PROBLEM
Problem is file is not moving from storage to app directory.
This is the actual function I am using to move file.
private boolean moveFile(File source, File destination) {
boolean isDirectoryMade = false;
// creates directory if not exists
if (!destination.getParentFile().isDirectory()){
File parent = destination.getParentFile();
isDirectoryMade = parent.mkdirs();
}
// rename or move file.
boolean isFileRenamed = source.renameTo(destination);
return isDirectoryMade && isFileRenamed;
}
First, you'll have to copy that file to the app directory, reading the file using Storage Access Framework.
Then, still using SAF, you'll have to ask the user for delete the original one.
For both steps, Android now needs you to ask the user for accessing public directories, specifying if you read the file (the user will have to select the file manually) and delete it.
To ask the user for Document read, you'll have to use the following :
val selectFileRequest = registerForActivityResult(OpenDocument()) {
result: Uri? ->
//Your code to copy the file here, the provided Uri is the selected file's
//Then you can delete the file with the following:
if(result != null)
{
//DocumentFile.fromSingleUri(this, result)?.delete()
//or
//DocumentsContract.deleteDocument(getContentResolver(), result);
}
}
Don't forget to add the needed permissions in your Manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28"/>
In the end, just call the following in your code:
selectFileRequest.launch(
arrayOf(
//Any Mime type you want to target, like the followings :
"application/pdf",
"image/*",
"text/*"
)
)
Related
I am trying to access my android files through my apk and (initially) list them on my terminal. This is the code I use:
File basePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)getAbsolutePath();
File directory = new File(basePath);
System.out.println("" + directory.toString());
File[] directoryContents = directory.listFiles();
I do succeed printing this path: /storage/emulated/0/Download which actually exists in my android and has some files in it.
When listing files inside that directory using:
for (File file : directoryContents)
{
if (file.isFile())
System.out.println("" + file.getName());
else
continue;
}
I get java.lang.NullPointerException: Attempt to get length of null array
I also included <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> in android's manifest.
My smartphone runs on Android 7.0 if that's of any help.
listFiles returns an array if the File instance from which this method is called from is a directory. Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) always(i guess) returns a directory( unless you altered the os defaults). so the only thing going wrong is probably lack of permissions;
here is how to ask permissions properly
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS replace this line instance of Environment.getExternalStorageDirectory()getAbsolutePath() issue will resolved.
I have the code bellow:
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/data/data/com.example.stavr.mydiary";
File file=new File(path);
File[] files = file.listFiles();
String arr[]=file.list();
List l=new ArrayList<>();
for(String i:arr){
if(i.endsWith(". txt")){
l.add(i);
}
}
which returns 0 files on my array (NullPointerException to be exact), Iknow that there are files in that directory. If i change the directory to just
Environment.getExternalStorageDirectory().getAbsolutePath()
the code work and it returns all the files. I thing that i have done something wrong with the permissions. Could you please help me,
Thank you very much in advance..!!!
It seems you're trying to access your internal app data folder, you can do that by using a context object:
String dir = context.getFilesDir().getAbsolutePath();
If you still want to access external storage then you should make sureyou have WRITE_EXTERNAL_STORAGE permission in your AndroidManifest.xml
I am looking to get the file path of a folder and then get its content. The folders are a public folder that you can access by just connecting the device into the computer. How do I go about getting a the file path to get access to these public folders and then get all its content?
So once I connect my computer to the device these are the folders I see and there is one that says "Folder to get items from" and I can't seem to figure what the file path is in order to get access to its content .
This is how I'm trying to get its content and Log them
File fileOfEpubs = new File("/data/data/Folder of to get items from/");
File[] dirEpub = fileOfEpubs.listFiles();
if (dirEpub.length != 0){
for (int i = 0; i < dirEpub.length; i++){
String fileName = dirEpub[i].toString();
Log.i("File", "File name = " + fileName);
}
}
You appear to be looking at the root of external storage. Programmatically, you access that via Environment.getExternalStorageDirectory(). That requires either the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permission.
You may need to escape the spaces in your string
File fileOfEpubs = new File("/data/data/Folder\ of\ to\ get\ items\ from/");
I want to implement dropbox in my java project.
User: If suppose you want to take a printout, instead of carrying a pendrive or sending it to your gmail id, you will just drop that file into on of the folder inside the public folder of the dropbox.
So after reaching the printout shop you will just navigate to the link http://{host}/myfiles. Here it will show the list of file which are there in that perticular folder inside the public dropbox folder, after clicking of a perticular list item it wll download the file, then the user can select a file and give print.
Is there a way to get the file list along with public url in dropbox using Java ?
You can use the createShareableUrl method to get a link for viewing the document. To get the file list, you can try
DbxEntry.WithChildren listing = client.getMetadataWithChildren(root);
The listing is a list of DbxEntry object of the folder. It can be either a file or a folder. For folder you just need do the same thing repeatedly until reach the end.
In Android case, you can create objects DropboxLink for each path in the folder you want, for example, "/Public/", and get their parameter url:
private DropboxAPI<?> dropbox;
...
ArrayList<String> files = new ArrayList<String>();
try {
Entry directory = dropbox.metadata(path, 1000, null, true, null);
for (Entry entry : directory.contents) {
files.add(entry.fileName() + ": "+ files.add(entry.path));
DropboxLink link = dropbox.share(entry.path);
files.add(link.url);
}
} catch (DropboxException e) {
e.printStackTrace();
}
I see a bunch of other people asking this same question, but none of the solutions posted helped me.
I'm trying to write a (binary) file to external storage from my Android app.
I put <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> into my manifest, but I still can't manage to create any files. The code I'm using to create files is
File folder = new File(Environment.getExternalStorageDirectory(), SAVE_DIRECTORY);
File toWrite = new File(folder, "save.bin");
if(!toWrite.exists()){
try {
if(!folder.mkdirs())
Log.e("Save", "Failed to create directories for save file!");
toWrite.createNewFile();
} catch (IOException e) {
Log.e("Save", "Failed to create save file! " + e.getMessage());
}
}
The call to mkdirs() fails, and the createNewFile() throws the IOException (ENOENT, because the directory doesn't exist)
Anybody know what's up? I've even tried rebooting my device. I'm on API level 8 on a Nexus 7, if it makes any difference.
first you should check the ExternalStorageState
public static boolean isSDCARDAvailable(){
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
if this method isSDCARDAvailable return true, then use your code
add the permissions:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
The documentation says that starting in API level 19, WRITE_EXTERNAL_STORAGE is not required to read/write files in your application-specific directories returned by getExternalFilesDir(String) and getExternalCacheDir(). However if you don't want to write files there and instead want to write files to getExternalStorageDirectory(), under API 23 or higher you have to request permission at run time using requestPermissions(). Once I did that I was able to create a directory in getExternalStorageDirectory().
I was suffering this issue as well and everything was properly configured in my app, i.e., I had the read and write permissions for external storage.
My problem was in the way I was creating the path to store my files:
private val LOG_BASE_PATH = Environment.getExternalStorageDirectory().path + "myFolder"
Note that it is necessary to include the "/" as follows:
private val LOG_BASE_PATH = Environment.getExternalStorageDirectory().path + "/myFolder/"
Without this, you won't be able to create the folder. Android won't fail, so you might think that there are issues with your phone configuration or app permissions.
Ideally, this helps somebody to save some precious time.