Access File from Removeable Storage in Android - java

I am trying to access a file placed in my remove able memory card.
What I am using is
File f=new File("/mnt/sdcard/CAPP/"); // f.exists() returns True
File f=new File("/mnt/sdcard/CAPP/myfile.apk"); // f.exists() returns False
Any idea why its happening so ? Although myfile.apk is placed in CAPP folder.
Thanks in advance.

Please try this...
String getFile = Environment.getExternalStorageDirectory().toString() + "folder name" + fileName;
File file = new File(getFile );

File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/myfile.apk");

Related

How to get absolute path from FileDialog?

I'm creating FileDialog and trying to get a FilePath for FileDialog object.
FileDialog fd = new FileDialog(this, "Open", FileDialog.LOAD);
fd.setVisible(true);
String path = ?;
File f = new File(path);
In this codes, I need to get a absolute FilePath for using with File object.
How can I get filepath in this situation?
You can combine FileDialog.getDirectory() with FileDialog.getFile() to get a full path.
String path = fd.getDirectory() + fd.getFile();
File f = new File(path);
I needed to use the above instead of a call to File.getAbsolutePath() since getAbsolutePath() was returning the path of the current working directory and not the path of the file chosen in the FileDialog.
Check out File.getAbsolutePath():
String path = new File(fd.getFile()).getAbsolutePath();

Save to desktop without the exact path

I want to save a file in my desktop. So I have
FileOutputStream out = new FileOutputStream(new File("C:\\path_to_Dekstop\\print.xls"));
and it works. But I want to save the file without put the exact path to the desktop. I searched it and I found similar questions and I came up with this solution:
File desktopDir = new File(System.getProperty("user.home"), "Desktop");
System.out.println(desktopDir.getPath() + " " + desktopDir.exists());
String pathToDesktop = desktopDir.getPath();
FileOutputStream out = new FileOutputStream(new File(pathToDesktop));
but I got an error
java.io.FileNotFoundException: C:\Users\nat\Desktop (Access is denied)
pathToDesktop represents the directory of the Desktop, you should supply a file name to write to
FileOutputStream out = new FileOutputStream(new File(desktopDir, "File to be written to"));
Which will place the "File to be written to" on the desktop
You can't write directly to Desktop as its a folder but not a file. You need to write to a file. DO something like thi s:-
File desktopDir = new File(System.getProperty("user.home"), "Desktop");
System.out.println(desktopDir.getPath() + " " + desktopDir.exists());
String pathToDesktop = desktopDir.getPath();
FileOutputStream out = new FileOutputStream(new File(pathToDesktop+System.getProperty("file.separator")+"print.xls"));
This will write to print.xls in Desktop.

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.

how do we know that a file is read protected?

In Java on Windows, how do we know that a file or folder is read-protected?
I try with canRead() et setReadable() :
String pathFile = "D:/Folder";
File f = new File(pathFile);
System.out.println("Is Protected => " + f.setReadable(true)==true);
but it not solve my problem
Thank you
canWrite method is true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise.
File lFile = new File("Sample.txt")
lFile.canWrite();

Filehandling file path

Basically i have two questions. i am using the below code to read and write z text file.
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append("my text here");
myOutWriter.close();
this create a new file every time i want this to OPEN_OR_CREATE(if file already exist don't create a new one)
Ad my second question is that how to change the path "/sdcard/mysdfile.txt" i want this file to stored in my sdcard -> subFolder1 -> SubFolder2
Thnaks
Do not use hardcoded /sdcard or /mnt/sdcard or your app will fail as devices vary on location or mountpoint of that storage. To get the right location use
Environment.getExternalStorageDirectory();
See docs here.
To append content to existing file use new FileOutputStream(myFile, true); instead of just new FileOutputStream(myFile); - see docs on that constructor here.
As for
how to change the path "/sdcard/mysdfile.txt"
Aside from getting rid of /sdcard as said above, just add subfolders to the paths: MyFolder1/MyFolder2/mysdfile.txt. Note these folder have to exists or the path will be invalid. You can always create it by calling myFile.mkdirs().
Replace
FileOutputStream fOut = new FileOutputStream(myFile);
with
FileOutputStream fOut = new FileOutputStream(myFile, true); //true means append mode.
Appart from that I have one suggestion for you.
Never never hardcode /sdcard in code,Rather consider writing.
File myFile = new File(Environment.getExternalStorageDirectory(),"mysdfile.txt");
Try my solution to write to end of text file
private void writeFile (String str){
try {
File f = new File(Environment.getExternalStorageDirectory().toString(),"tasklist.txt");
FileWriter fw = new FileWriter(f, true);
fw.write(str+"\n");
fw.flush();
fw.close();
} catch (Exception e) {
}
}
*File(Environment.getExternalStorageDirectory().toString()+"your/pth/here","tasklist.txt");
File dir = Environment.getExternalStorageDirectory();
File f = new File(dir+"/subFolder1/",xyz.txt); <-- HOW TO USE SUB FOLDER
if(file.exists())
{
// code to APPEND
}
else
{
// code to write new one
}
1> OPEN_OR_CREATE
You can try or can replace MODE_APPEND with true like #Vipul's suggestion
FileOutputStream fOut = openFileOutput(your_path_file, MODE_APPEND);
//it means if the file is exist the content you want write will append into it.
2> stored in my sdcard -> subFolder1 -> SubFolder2
you can use Environment.getExternalStorageDirectory().getAbsolutePath() to get full file path the SDCard. Then concat strings to get the file path you want. Ex:
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";
File f = new File(baseDir + File.separator + subfolder1 + File.separator + subfoler2, fileName);
In Java 7 we can do it this way:
Path path = Paths.get("/sdcard/mysdfile.txt");
BufferedWriter wrt = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

Categories