Android unable to create new directory on external storage - java

Unable to create a new directory in Android external storage for some reason, Im assuming there is something im missing but not able to spot it below is my code which I am using to attempt to create the directory, any help will go a long way thanks
Calendar calendarTime = Calendar.getInstance();
String newFolder = "/NewFolder/videos";
File newDirectory = new File(Environment
.getExternalStorageDirectory().toString() + newFolder);
newDirectory.mkdir();
File file = new File(newDirectory,
String.valueOf(calendarTime.getTimeInMillis()) + ".mp4");
if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.THREE_GPP) {
recorder.setOutputFile(file.getAbsolutePath());
} else if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.MPEG_4) {
recorder.setOutputFile(file.getAbsolutePath());
} else {
recorder.setOutputFile(file.getAbsolutePath());
}
and in my manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

File.mkdir() will only create the directory if its parent exists. In this case, the directory you want to create is "videos" and its parent is "NewFolder". "videos" will not be created if "NewFolder" does not exist. If you want to create both directories at once, you should use File.mkdirs() instead.

I was stuck with issue of folder not getting created for 2 days. Code was perfect, tried multiple code options but none worked. Ultimately I rebooted by device - Nexus 4 and reconnected to my Windows 7 laptop for debugging. I was able to see all files and the directory in Windows 7 explorer. Looks like it was just issue with Nexus 4 (kitkat) not refreshing the folder structure and it was also not visible on Windows 7 explorer and was not working with my app.
Also after restart of Nexus 4 the error from call mediaRecorder.start() "not able to start" also disappeared and all files and directories my app is creating appeared.

Do not forget to ask for WRITE_EXTERNAL_STORAGE permission explicitly.
Here is how to do that: https://developer.android.com/training/permissions/requesting

Related

Windows 10 - ObjectOutputStream can't find relative paths because current working directory is System32

When I call method
System.out.print(new File("").getAbsolutePath())
from main I get the project workspace
C:\Users\darkr\Desktop\NuovoWorkSpace\ProjectName.
When it gets called by our save() method, which serializes what we need, suddenly the absolute path given from
new File("").getAbsolutePath()
becomes System32 (for me) and Desktop directory for my colleagues.
We're using gitHub to share our changes but this makes it almost impossible.
The code you have new File("").getAbsolutePath() is commonly used to determine the current directory from where you launched your application's main(String[]) method. So it looks like you are running from C:\Windows\System32 not on desktop folder.
The easiest way to fix your issue is to edit your application shortcut (see .lnk file and set "Start in" folder), or cd to be in an appropriate writable directory before running your application, or change your application to use file chooser to pick the target location for saves.
Alternatively pick sensible output paths for writing to instead of "", some good candidates are:
// Local user profile
File folder = new File(System.getenv("LOCALAPPDATA"), "myfolder");
// Roaming user profile
File folder = new File(System.getenv("APPDATA"), "myfolder");
// Temp folder:
File folder = new File(System.getProperty("java.io.tmpdir"), "myfolder")
Some sites suggest one of the following lines to locate Desktop, but this is unreliable because it will not work if the folder has been moved or run on some non-English installations:
File maybeDesktop = new File(System.getProperty("user.home"), "Desktop");
Path maybeDesktop = Path.of(System.getProperty("user.home"), "Desktop");
If you want to read the exact location of user Desktop from Java, you need to use JNI/JNA/Panama call to Windows API functions SHGetFolderPath or SHGetKnownFolderPath.

Location of file saved to Android folder

I'm following along this thread, and calling saveFrames
MediaMetadataRetriever.getFrameAtTime() returns only first frame
He is saving in Environment.getExternalStorageDirectory()+ "/videos/frames/" . Which turns out to be "/storage/emulated/0" . When I click on device explorer and "/storage/emulated" it says "Permission denied". Is there a way to access this, or is there another place that I can store the data?
Update:
So here's how I solved it. I can cd to that /storage/emulated/0 using adb shell. However I cannot write to it. I change the directory name to
String folder = this.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/frame/" ;
I can see all the files there. To retrieve the files and view them, I use
adb pull /storage/emulated/0/Android/data/com.example.<app>/files/Pictures/frame
Here are more detailed discussions on storage permissions:
WRITE_EXTERNAL_STORAGE when targeting Android 10
Android Studio - How to use getExternalFilesDir
https://developer.android.com/training/data-storage/manage-all-files
https://support.google.com/googleplay/android-developer/answer/10467955
https://developer.android.com/training/data-storage
requestLegacyExternalStorage is not working in Android 11 - API 30
https://www.dev2qa.com/android-read-write-external-storage-file-example/

Android Studio cannot read from file, does not exist

I'm trying to read from a file in Android Studio, in a small Java app. So I'm trying this:
File test = new File("C:\\testing\\testFile.dat");
if (test.exists()) {
System.out.println("test exists");
}
else {
System.out.println("test doesn't exist");
}
The file definitely exists, but it keeps on reporting that the file doesn't exist. I was able to work around this with another file by using the AssetManager and reading it through a stream, but the method I'm calling now requires a File's absolute path, but it's point blank refusing to find the file.
Am I doing something dumb, or misunderstanding something?
UPDATE
Ok, thanks for the input, I've now solved the problem. First I had to upload the file I wanted into the virtual device's storage, then I was able to get the path to it.
File test = new File(this.getFilesDir().getAbsolutePath(), "testFile.dat");
but the method I'm calling now requires a File's absolute path
Assets are files on your development machine. They are not files on the device.
Ideally, you switch to some library that supports InputStream or similar options, rather than requiring a filesystem path. If that is not an option, you can always get the InputStream from AssetManager and use that to make a copy of the data in some file that you control (e.g., in getCacheDir()). You can then pass the path to that file to this method.
You can place this file in your assets/ folder inside the android project and access using the following code.
val inputSteam = assets.open("testFile.dat")
or place it inside the res/raw folder and access it like below.
val inputStream = resources.openRawResource(R.raw.testFile)
We can't access a file on a development machine like this and won't be available on an android device so it will break so it's better if we move this somewhere inside the project and access it as above.

fopen in JNI C code get failed for file placed in assets folder in android application

I have kept some files in assets folder of android application.
Now i compile that application and get apk. [when i extract that apk my files are there in assets folder]
Now i install that apk in mobile device
and in That application has some code in c programing with JNI interface.
Now my fopen() call in c programming for that file get failed.
fopen("myfile","r");
I know while installing apk android copy assets file to /data/data/com.packagename/something
So does anyone knows that path so i can give it in fopen()
or is there any other method to open that file in C programming.
If i keep those files in sdcard folder and access like fopen("/sdcard/myfile","r"); then it works file. But i want to keep those files in assets folder only
You can use the asset manager to access assets in JNI code. It's part of NDK.
http://developer.android.com/ndk/reference/group___asset.html
Something like:
EXPORT_API void LoadAsset(char* filename, jobject assetManager){
AAssetManager* mgr = AAssetManager_fromJava(env, assetManager);
AAsset* asset = AAssetManager_open(mgr, filename, AASSET_MODE_BUFFER);
AAsset_read(asset, ...);
}
And then in Java something like:
LoadAsset("myfile", getContext().getAssetManager());
One way I've found is to write a test line in the code, something like:
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
Now, if you know where your assets are stored by Android, /data/data/com.packagename/assets/file.png, for example, then you will know the reletive or absolute path to the assets. I hope this works for you, it helped me!

Can't find folder or file created with Android App with windows file exlorer

I'm creating a directory and a text file on the sdcard in one of my apps because I want to be able to move it to my computer for analysis. But I can't find the folder or the file I'm creating on my sdcard using the file browser on my computer.
I CAN find and read the file using my phones file manager but not using the file browser in windows.
So the file and folder are succesfully created and I can write to the file, I can also find and read the file using the file manager on my phone but I can't find either directory or file using my computer.
I have a uses permission for the application to allow it to write to external storage.
This is the code I use to create the file and directory.
String fileName = "testFil.txt";
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/PulsApp";
File appDirectory = new File(path);
appDirectory.mkdirs();
File file = new File(path, fileName);
try {
file.createNewFile();
} catch (IOException e) {
}
Does anyone know what the problem is and how to fix it? I really need to be able to write files to my sdcard so I can transfer them to my computer.
I am completely baffled by this problem since all the research I've done point to that everyone else is doing the same thing.
If your device is running Android 3.0 or higher, you also need to use MediaScannerConnection to index your newly-created file before it will show up on a development PC's file explorer.
More accurately, the newly-created file needs to be indexed by the MediaStore. That will eventually happen for other reasons (e.g., device reboot). However, you are better served using scanFile() on MediaScannerConnection to get it to happen more quickly.
I blogged about this last summer.
Sometimes that the MediaScannerConnection will recognize the folder as a unknown type file, so try to create another folder inside the original one can avoid this problem.
I have met the same problem, and I use the method in the comment
And it works for me.

Categories