mkdirs() doesn't work on Gingerbread? - java

I'm trying to create a folder that contains a subfolder inside. I wrote this code
File myFolder = new File(Environment.getExternalStorageDirectory().getPath().toString()
+ File.separator+"Folder/SubFolder"+File.separator);
myFolder.mkdirs();
Log.d("test", "creating the folders");
if (myFolder.exists()) {
Log.d("test", "folder created");
} else {
Log.d("test", "there is an error");
}
In my logcat I see the folder created and there is an error.
Obviously, I've added the
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
permission. Where is the problem?

try removing the File.separator from the file path
File myFolder = new File(Environment.getExternalStorageDirectory().getPath().toString()+File.separator+"Folder/SubFolder");
then check if the path exists, if not create the folders.
if(!myFolder.exists())
myFolder.mkdirs();

use below code.
File myFolder = new File(Environment.getExternalStorageDirectory().getPath().toString()
+ File.separator + "Folder/SubFolder")

Related

how can i get the list of all files Inside a folder

please how can I list all files inside a folder?
I try to do that with that code
File theFolder = new File(Environment.getExternalStorageDirectory()+File.separator +"TestFolder");
if(theFolder.exists())
{
Log.d("theFolder", "theFolderExiste ");
File [] files = theFolder.listFiles();
Log.d("Files", "files: "+files.length);
for(File file : files)
{
Log.d("file ", "file name : "+file.getName());
}
}else
{
Log.d("theFolder", "we dont have that folder ");
}
but hi give me that error
Caused by: java.lang.NullPointerException: Attempt to get length of null array
at com.joshuabutton.documentscanner.DisplayListOfFiles.onCreate(DisplayListOfFiles.java:76)
and I have files inside that folder as you can see in that pic
In order to access the files, the permissions must be given in the manifest file.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Try this:
String path = Environment.getExternalStorageDirectory().toString()+"/Pictures";
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
Log.d("Files", "FileName:" + files[i].getName());
}
There's two things you need to take in consideration.
1 - You need a read storage permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> to be able to read data that your app did not create
2 - Even with read storage permission, newer versions of android, do not allow to read folders this direct, check out this video, it might help you

How to hide existing folder in Android?

I have a existing folder (Old Folder name : xyz) in Sdcard, Whenever I try to rename this folder (New Folder name : .xyz) using toRename(). It return false and create a new folder (name : .xyz). Old Folder (name : xyz) is also visible in sdcard.
How to rename the existing folder to make a that Folder hidden in Android?
String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/xyz";
File file = new File(dir);
StringdirHide = Environment.getExternalStorageDirectory().getAbsolutePath() + "/.xyz";
File fileHide = new File(dirHide);
if (!file.exists() && !fileHide.exists())
{
fileHide.mkdir();
}
else if(file.exists())
{
file.toRename(fileHide);
}
The method to rename is renameTo. The following code should work. Tell me if you face any problems.
String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/xyz";
File file = new File(dir);
String dirHide = Environment.getExternalStorageDirectory().getAbsolutePath() + "/.xyz";
File fileHide = new File(dirHide);
if (file.exists() && !fileHide.exists()) {
file.renameTo(fileHide);
} else if(!file.exists()) {
fileHide.mkdir();
}
#Akashsingla19 I think problem is the folder u want to rename is not exist run following code Twice hope you will get your answer
if (!file.exists())
{
file.mkdir();
}
else if(file.exists())
{
file.renameTo(fileHide);
}
In your code you are using some toRename() method, which i couldn't found anywhere in File class in android. Actual method of File class in android to rename folders and files is renameTo(). Check this method and try to use it and revert please.
Thanks.

android - reading user created file

Couldn't find too much about how to read a file that isn't somewhere on the SD card or storage, but rather right there in the android project directory.
I keep getting a FileNotFoundException. This is how I declare the file,
File SPPolicy = new File("SHPR_policy");
I've gotten the same error when putting it in the src/ directory, the src/[[package]]/ directory and the main project directory, and I get this error:
java.io.FileNotFoundException: /SHPR_policy: open failed: ENOENT (No such file or directory)
Is there a certain place I have to put this file? Is it because my file doesn't have an extension (I noticed the "/" before SHPR_policy but I didn't think it would be a problem because Eclipse let me create a file without an extension)?
Save the file in raw folder and try the below code.
try
{
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.test);
byte[] b = new byte[in_s.available()];
in_s.read(b);
txtHelp.setText(new String(b));
} catch (Exception e) {
// e.printStackTrace();
txtHelp.setText("errr.");
}
Use these piece of code to check if the file was already created:
File f;
f=new File("myfile");
if(!f.exists()){
f.createNewFile();
}
Also, if you want to allocate your file in the external directory you can use these code:
File newxmlfile = new File( Environment.getExternalStorageDirectory() + "/new.xml");
XmlSerializer serializer = Xml.newSerializer();
try {
newxmlfile.createNewFile();
} catch (Exception e) {
Log.e("IOException", "exception in createNewFile() method", e);
}
And, did you added the permission in the manifest to be able to manipulate files?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You should place the file in the assets folder and use this:
InputStream ims = getAssets().open("SHPR_policy");

File object can't find the file when there is one

In my app After user clicks on a button ,the download manager starts to download a file from internet and saving it to the internal sd card using this code:
void startDownload()
{
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs();
download_req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle(PersianReshape.reshape("Downloading"))
.setDescription(PersianReshape.reshape("currently downloading the file..."))
.setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory().getAbsolutePath() , packageId + ".sqlite");
download_ID = mgr.enqueue(download_req);
}
After it is downloaded, I plan to check its existance everytime app runs with this code:
String DatabaseAddress =
Environment.getExternalStorageDirectory().getAbsolutePath() +
"/ee.sqlite";
File file = new File(DatabaseAddress);
Log.d("PATH File: ", DatabaseAddress);
if (file.exists()){
Toast.makeText(getApplicationContext(), "found", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "not found", Toast.LENGTH_SHORT).show();
}
Now when I run this code it returns "not found" message whereas the file is already there (I checked its existance using a file manager).
the device I test on is nexus 7 and path used in saving the download file is: /storage/emulated/0/ee.sqlite
ee.sqlite is the filename of downloaded file.
/storage/emulated/0/ is the default path returned by app
Permissions added to manifest for this code are:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Q: Why does file.exists() returns false when there is a file?
UPDATE:
WHEN I USE HARDCODE
File temp = new File("/sdcard/storage/emulated/0/", "ee.sqlite");
it works but when I use Environment.getExternalStorageDirectory().getPath() it doesn't.
Just initialize the File like this:
Updated:
This is just because of the separator missing there:
public static File getExternalStorageDirectory() {
return EXTERNAL_STORAGE_DIRECTORY;
}
and EXTERNAL_STORAGE_DIRECTORY is:
private static final File EXTERNAL_STORAGE_DIRECTORY
= getDirectory("EXTERNAL_STORAGE", "/sdcard");
static File getDirectory(String variableName, String defaultPath) {
String path = System.getenv(variableName);
return path == null ? new File(defaultPath) : new File(path);
}
String baseDir = EXTERNAL_STORAGE_DIRECTORY ;
String fileName = "ee.sqlite";
// Not sure if the / is on the path or not
File file = new File(baseDir + File.separator + fileName);
if (file.exists()) {
Toast.makeText(getApplicationContext(), "found", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "not found", Toast.LENGTH_SHORT).show();
}
2nd Possibilites: As you are running it in emulator you have to make sure you have external storage enabled Like this:
In Eclipse, go to Window > Android SDK and AVD Manager. Select the appropriate AVD and then click Edit.
Make sure you have SD card support enabled. If you do not, click the "New" button and select the "SD Card Support" option.
Finally got it to work by changing the File object.
The solution is to change the File object to the following:
File file = new File(Environment.getExternalStorageDirectory().getPath() + dirName + File.separator , fileName);
where dirName is:
String dirName = Environment.getExternalStorageDirectory().getAbsolutePath();
and fileName is:
String fileName = "ee.sqlite";
so I could easily check whether file exist or not using my criteria function.
if (file.exists()){
Toast.makeText(getApplicationContext(), "found", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "not found", Toast.LENGTH_SHORT).show();
}
I like to thank #andru for helping me.

new File(path) always actually creates a file on android?

I am trying to check if a file exits on android sd card...so i do:
File f=new File(sdpath + "/" + DATABASE_NAME); //
if(!f.exits()) {
...create new file..
}
else {
...do something...
}
Every time this actually creates the directory or file on the sd card.
I know it doesnt exist, and when the new File is executed it is created and it shouldnt ?
I read all across google that new File doesnt create an actual file on the file system , but in my case it does...
Any alternatives to checking if a File/directory exits without using new File..
Edit 1: Well I'd just like to add (after 4 years :)) that this problem occurred only on two devices at the time i was writing the post and never again, one of them was HTC Desire C with android 4.0 and the other was some Huawei with android 2.x, cant remember anymore.
For some strange reason it turned out that new File created a directory every time...
instead of checking if (!f.exists()), I changed it to checking if (!f.isFile())
In that case i create a new file and it works good, the next time i run it the file is already on the sd card...
The way that worked was nearly like yours:
File f = new File(Environment.getExternalStorageDirectory(), "a directory");
if(!f.exists){
// do something
}
and to check whether a file exists or not is almost the same way:
File f = new File(Environment.getExternalStorageDirectory() + "/a directory/" + "a file");
if(!f.exists){
// do something
}
I hope it can help you out, because it didn't create a file or directory in my app. It just checked the path.
this may helps you, try like
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//handle case of no SDCARD present
} else {
File file = new File(Environment.getExternalStorageDirectory()
+File.separator
+"myDirectory" //folder name
+File.separator
+"myFile.example"); //file name
if(file.exists()){
Toast.makeText(MainActivity.this, "Not Create ", 12).show();
}else{
file.mkdirs();
Toast.makeText(MainActivity.this, "Create ", 12).show();
}
}
Try this
File[] files = filedir.listFiles();
for (File file2 : files) {
if (file2.isDirectory()) {
Toast.makeText(this, "directory", Toast.LENGTH_LONG).show();
} else {
if (file2.getName().equals(DATABASE_NAME)) {
Toast.makeText(this, "File found",Toast.LENGTH_LONG).show();
}
else{Toast.makeText(this, "File not found",Toast.LENGTH_LONG).show();
}
}
}

Categories