How to create a new folder in android? - java

I want to create a new folder in external storage. I use this code:
val folderMain = "name"
val f = File(getExternalStorageDirectory(), folderMain)
if (!f.exists()) {
f.mkdirs()
}
After executing it works and creates a new folder in internal storage, not in external storage. How can I create a new folder in external storage?
I am 100% sure I have external storage in my device and it has 14 GB space available in it and location is /storage/extSdCard.
I have tested this code on two Samsung phones Android version jellybean and Kitkat but the same result.

You can have the answers to your questions here :
https://developer.android.com/training/data-storage
I also recommend you to check the result of mkdirs():
if (!f.exists() && !f.mkdirs()) {
Log.e("mDebug", "Couldn't create " + f.getName());
}

After executing it works and creates a new folder in internal storage, not in external storage.
No, it creates the file in what the Android SDK refers to as external storage.
I am 100% sure I have external storage in my device and it has 14 GB space available in it and location is /storage/extSdCard.
That represents removable storage.
How can I create a new folder in external storage?
Your existing code creates a directory in the root of external storage. You have no ability to write to arbitrary locations on removable storage.
The simplest places to write to on removable storage are in the locations supplied by the getExternalFilesDirs(), getExternalCacheDirs(), and getExternalMediaDirs() methods on a Context. If those return 2+ locations, the second and subsequent ones are on removable storage, and you have full read/write access to them.

try this code:
String fileName = "myfile.zip";
File ZIP_Directory = new File("/sdcard/MOBstate/");
ZIP_Directory.mkdirs();
File outputFile = new File(PDF_Directory, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);

Related

How do I compress image in android studio(JAVA) and store it in device specific folder

I am making an app for image compression And I am new to Android development....So my problem is as we have some issue with accessing External storage in JAVA......I have Tried
compile 'id.zelory:compressor:2.1.0'
compressedImage = new Compressor(this)
.setMaxWidth(640)
.setMaxHeight(480)
.setQuality(75)
.setCompressFormat(Bitmap.CompressFormat.WEBP)
.setDestinationDirectoryPath(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
).getAbsolutePath()
)
.compressToFile(actualImage);
Okayy...so can I use WEBP_LOSSLESS instead of WEBP for Android API 30?
and The main issue is how do I set the destination for storing in Specific Folder?
The red deprecation box of getExternalStoragePublicDirectory lists alternatives:
Apps can continue to access content stored on shared/external storage
by migrating to alternatives such as
Context#getExternalFilesDir(String),
MediaStore,
or
Intent#ACTION_OPEN_DOCUMENT.
Bitmap.CompressFormat.WEBP also contains a deprecation notice:
This field was deprecated in API level 30. in favor of the more
explicit
CompressFormat#WEBP_LOSSY
and
CompressFormat#WEBP_LOSSLESS.
For example, something like this should work:
Context ctx = this;
File storeFolder = ctx.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
compressedImage = new Compressor(this)
.setMaxWidth(640)
.setMaxHeight(480)
.setQuality(75)
.setCompressFormat(Bitmap.CompressFormat.WEBP_LOSSLESS)
.setDestinationDirectoryPath(
storeFolder.getAbsolutePath()
)
.compressToFile(actualImage);

Save file to internal storage in Android

I want to make a simple Android application which will make user write text and when he presses on save button I'll get the text from text area and create folder then save file into folder in the storage.
I did that but in external storage and here's my code
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/newfolder";
File f = new File(path);
f.mkdir();
PrintWriter pw = new PrintWriter(path + "/" + txt_name.getText() + ".txt");
pw.write(main_txt.getText().toString());
pw.close();
This code runs well but it runs only on devices which have an external memory card, so I want to do the same but save file on internal storage for device to make this code run on any device, how can I save file into internal storage?
No.
Your code saves to external memory which is build into the phone.
Your code has nothing to do with a removable micro SD card.

How to save a file to external storage in the media directory in 2020?

I have a question.
How can I save a file from network to the external storage of the android device, with
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)
being depricated?
My Code:
private void download(Context mContext) throws IOException {
String requestUrl = "http://someresource/..."
URL url = new URL(requestUrl);
InputStream in = url.openStream();
mContext.getFilesDir();
URI uri = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MUSIC).toURI();
Files.copy(in, Paths.get(uri.getPath() + "/_test.mp3"), StandardCopyOption.REPLACE_EXISTING);
in.close();
System.out.println("finished!");
}
I get the error W/System.err: java.nio.file.AccessDeniedException: /storage/emulated/0/Music/_test.mp3
I also read the article https://developer.android.com/training/data-storage/shared/media#java
but I suppose this is meant to be more of a guideline to tamper with existing media files, like searching or editing file tags etc. and not simply saving a file in the media directory.
Update:
My app needs to fulfill two tasks. I want to save an mp3 file to the above mentioned directory and also read files from this directory.
Below Q: Working with Environment.getExternalStorageDirectory().getPath()+"/Music"; returns the Music-Folder on the built-in flash memory of the Android device.
In that manner I want to know how to get the Music-Folder on the SD-Card of the Android device (when its plugged in).
Since Q: the above Method returns a directory, which is no longer directly accessible to apps. The tasks I want to fulfil are the same as the ones mentioned above.
As #blackapps supposed, using the MediaStore Class is in Q preferable. But how exactly do I do that?
For android 10 and 11 add this line to your <application> element in the android manifest file.
hope it will work:
<application
android:requestLegacyExternalStorage="true"

How to remove A file from removable/secondary SD card

I want to delete a file from the removable sd card, I tried many ways but nothing did the job.
Tried:
file.delete();
and
File file = new File(selectedFilePath);
boolean deleted = file.delete();
and
DocumentFile documentFile = DocumentFile.fromFile(file);
documentFile.delete();
and
DocumentsContract.deleteDocument(context.getContentResolver(),
Uri.fromFile(file );
none of which deletes the file
I want to delete a file from the removable sd card
In general, you can't.
If you put the file in one of the Context locations (getExternalFilesDirs(), etc.), then you should be able to delete it, using delete() on a File object.
If this is some other file, you do not have permission to do anything with it, including delete it.
And on Android Q, you will not have much access to external or removable storage at all.
You are welcome to use the Storage Access Framework (e.g., ACTION_OPEN_DOCUMENT, ACTION_OPEN_DOCUMENT_TREE) and work with content that way.
i am trying to work on file explore
Android Q is severely restricting that entire app category. I recommend that you build something else.

File existence in internal storage using java

I am creating an application were i am reading the content from a file present in internal storage and displaying in the application.
I am creating a file on the desktop and transferring that file to the mobile using usb cable.If sdcard is present the file will be stored in sdcard and for accessing the file i found the following code and it worked for me.
File path = Environment.getExternalStorageDirectory();
/storage/sdcard0/Filename.txt is the path which i am getting when i run the above code.If file is present in sdcard it is returning true else false.
If sdcard is not present and when i transfer the file from desktop to mobile it gets stored in internal storage.in this case how do i access my file.
In some cases i have come to know that sdcard0 is internal storage and not the external storage.
Which is the best way to find the file existence in internal storage of the mobile and not apps internal storage. please help.
Thanks in advance
To find out the path for your app's internal storage you can use the following commands:
Context context = getApplicationContext();
or
Context context = getApplication();
String dir = context.getFilesDir().getAbsolutePath();
String dir = context.getFilesDir().getPath();
getFilesDir() returns a File object that you can get the path from there. Then you can use that path to transfer your file. Also read below.
See here on how to write a file to internal storage and here on getting the path for internal storage.
The following code gives you the path for the your file in internal storage and then you can open it:
String yourFilePath = context.getFilesDir() + "/" + "filename";
File yourFile = new File( yourFilePath );
You can also use the following approach explained in here
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis = context.openFileInput(filename);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
fileContent.append(new String(buffer));
}
The above solution opens input stream to the file name provided using the context that gives the location where the files are stored in internal storage. In the while loop it reads from the input stream (up to size of buffer) every iterator and adds the read data to StringBuilder instance. The loop terminates when the length of the read data from input stream is -1.
If the file is not found, FileNotFoundException will be throw by openFileInput(filename) method.

Categories

Resources