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

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();
}
}
}

Related

Android app says the file does not exist but it does. I need to install it

Here is my code:
String dir = getFilesDir().getAbsolutePath();
File myFile = new File(dir+"/file.apk");
if (myFile.exists())
{
textView.setText("File exists.");
}
else
{
textView.setText("File does not exist.");
}
myFile.exists() is false. I do not know why. The file exists and it is located in the directory.
When I solve the problem, I'll try this:
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(Uri.fromFile(myFile));
intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Can somebody help? Why it does not see the file?
UPDATE:
It's really strange. If I use code:
if (myFile.exists())
{
textView.setText("it exists");
}
else
{
textView.setText(myFile.getAbsolutePath());
}
, it goes to 'else' and shows the path to the file which 'does not exist'.
Thanks to greenapps:
"Please click in Astro app left to the word Primary on the up arrow to see the real path. /Primary/ does not exist on an Android device. It's an Astro invention. And Astro shows external memory with Primary. And take a better file explorer like ES File Explorer to inform you about real paths"
I used direct path I found using Astro (modified string dir to '/sdcard/data/data/...").
Try using this code:
String dir = getFilesDir().getAbsolutePath();
boolean fileExists = (new File(dir + "/file.apk")).isFile();
if (fileExists)
{
// your file exists
}
else
{
// your file does not exist
}
If you construct the file with the 2-arg constructor, you can avoid adding a system-dependent path separator character. Like this:
File myFile = new File(dir, "file.apk");

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.

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.

Why won't my file rename itself?

I am working on an android app and I want to rename a file. The problem is that it is not renaming:
File f = adapter.getItem(i);
File file = new File(f.getAbsolutePath(), "helloworld");
if (f.renameTo(file)) {
Toast.makeText(getActivity(), "done", Toast.LENGTH_LONG).show();
}
Solution BIg Thanks to #S.D.(see comments)
File f = adapter.getItem(i);
File file = new File(f.getParent(), "helloworld");
if (f.renameTo(file)) {
Toast.makeText(getActivity(), "done", Toast.LENGTH_LONG).show();
}
I think the issue is that:
File f = adapter.getItem(i);
Gives use some File f, say where f cooresponds to say: user2351234/Desktop. Then, you do:
File file = new File(f.getAbsolutePath(), "helloworld");
Which says to make a File file, where file cooresponds to: user2351234/Desktop/helloworld. Next, you call:
f.renameTo(file)
which attempts to rename f, user2351234/Desktop to user2351234/Desktop/helloworld, which doesn't make sense since in order for user2351234/Desktop/helloworld to exist, user2351234/Desktop would have to exist, but by virtue of the operation it would no longer exist.
My hypothesis may not be the reason why, but from Why doesn't File.renameTo(…) create sub-directories of destination?, apparently renameTo will return false if the sub-directory does not exist.
If you want to just change the name of the file, do this:
File f = adapter.getItem(i);
String file = f.getAbsolutePath() + "helloworld";
f = new File(file);
EDIT:
My proposed solution should work, but if my hypothesis about why your way does not work is incorrect, you may want to see this answer from Reliable File.renameTo() alternative on Windows?
Question 1: Do you see an exception or does it return false?
Question 2: Did you give permission for the app to write to the SD card? (I'm assuming that's where this file lies).
The permission to add is"
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This posting: How to rename a file on sdcard with Android application? seems to answer a similar question.
use this code.
File sdcard = Environment.getExternalStorageDirectory()+ "/nameoffile.ext" ;
File from = new File(sdcard,"originalname.ext");
File to = new File(sdcard,"newname.ext");
from.renameTo(to);

Can't delete file after being renamed (file is opened)

I am using icefaces to upload files to relative path in my web app (mywebapp/audio), then after the file is getting uploaded I rename it to save its extension as follows:
public static File changeExtToWav(FileInfo fileInfo,
StringBuffer originalFileName) {
log.debug("changeExtToWav");
int mid = fileInfo.getFile().getName().lastIndexOf(".");
String fileName = fileInfo.getFile().getName().substring(0, mid);
originalFileName.append(fileName);
log.debug("originalFileName: " + originalFileName);
String newFileName = fileName + "_" + new Date().getTime() + "."
+ "wav";
File newFile = new File(fileInfo.getFile().getParent() + "/"
+ newFileName);
log.debug("newFileName: " + newFile.getName());
fileInfo.getFile().renameTo(newFile);
return newFile;
}
after the file is getting uploaded, sometimes I want to delete it from UI button as follows:
try {
File fileToDelete = new File(filePath); // correct file path
log.debug("file exists: " + fileToDelete.exists()); // true
fileToDelete.delete();
} catch (Exception e) {
e.printStackTrace();
}
the file path is correct, and I get no exceptions, but the file is not deleted (I am using java 6 btw).
please advise how to fix this issue.
UPDATE: using the following useful method, I can get that the file is opened, any ideas how to close it ?
public String getReasonForFileDeletionFailureInPlainEnglish(File file) {
try {
if (!file.exists())
return "It doesn't exist in the first place.";
else if (file.isDirectory() && file.list().length > 0)
return "It's a directory and it's not empty.";
else
return "Somebody else has it open, we don't have write permissions, or somebody stole my disk.";
} catch (SecurityException e) {
return "We're sandboxed and don't have filesystem access.";
}
}
Well if the file is open, then there is two solutions :
You have a stream in your program open on this file. Note that afaik it's a problem on Windows, with Unix I can delete a File even if a stream is opened on it.
You have an other process using this file. So in this case you can't do anything from Java.
In the log it tells also that it can be a permission problem, are you sure you have enough privileges?
You can also use Files#delete(Path path) (jdk7) to have more details about the issue.

Categories