I am developing an Android app. I am still learning android. But I am having a problem with checking file in download folder exists or not. It is always returning false. But the file actually exists.
This is the function to check file exists or not in CommonHelper class
public static boolean fileExists(String path)
{
File file = new File(path);
if(file.exists())
{
return true;
}
else{
return false;
}
}
This is how I am checking files in built in download folder
if(CommonHelper.fileExists(String.valueOf(Environment.DIRECTORY_DOWNLOADS)+"/"+cursor.getString(1)))
{
//do other stuffs here
}
What is wrong with my code?
The problem is, that you are not getting the full path.
Try getting the path with Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
public static boolean fileExists(File path, String filename){
return new File(path, filename).exists();
}
And then call:
CommonHelper.fileExists(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), cursor.getString(1));
EDIT: Please note, getExternalStoragePublicDirectory can also be something else, like getExternalStorageDirectory() depending, on where you actually stored your file.
Try this:
File file = getContext().getFileStreamPath(file_name);
if(file.exists()){
FileInputStream fileIn= new FileInputStream(file);
...
}
you have to add the file name to the path when creating the file... Please try as below..
File file = new File(storagePath + "/" + fileName);
if (file.exists()) {
return true;
}
else
{
return false;
}
try this
if(CommonHelper.fileExists(new File(Environment.DIRECTORY_DOWNLOADS),cursor.getString(1)))
{
//do other stuffs here
}
and
public static boolean fileExists(File directory, String fileName)
{
File file = new File(directory,fileName);
if(file.exists())
{
return true;
}
else{
return false;
}
}
File file = new File(Environment.getExternalStorageDirectory() + "/filename");
if(file.exists){
return true;
}else{
return false;
}
Related
I am using android studio just to see how to create a file, or if a file already exists use the existing file. My code so far is:
public void saveFile(){
try{
FileOutputStream fOut = openFileOutput("current.xml",
Context.MODE_APPEND);
//OutputStreamWriter outputWriter = new
OutputStreamWriter(fOut);
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(fOut, "UTF-8");
serializer.startDocument(null, Boolean.valueOf(true));
serializer.startTag(null, "records");
serializer.startTag(null,"employee");
serializer.startTag(null, "name");
serializer.text("Ryan");
serializer.endTag(null,"name");
serializer.startTag(null,"surname");
serializer.text("Derk");
serializer.endTag(null,"surname");
serializer.startTag(null,"salary");
serializer.text("60000");
serializer.endTag(null,"salary");
serializer.endTag(null,"employee");
serializer.endTag(null,"records");
serializer.endDocument();
serializer.flush();
fOut.close();
Toast.makeText(getApplicationContext(), "Save Successful",
Toast.LENGTH_LONG).show();
}
catch(Throwable t){
Toast.makeText(getApplicationContext(), "Save Unsuccessful",
Toast.LENGTH_LONG).show();
}
}
private static String getValue(String tag, Element element) {
NodeList nodeList =
element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = nodeList.item(0);
return node.getNodeValue();
}
How can i check if the file is already created before saving to that file? And if it is not created create the file?
If I correctly understand your problem:
You need to have your application Context android.content.Context to call the method openFileOutput.
Also, to check if the file exists, you can call Context.fileList() to get the list of files in the context and check if your files exist.
String[] files = fileList();
for (String file : files) {
if (file.equals(myFileName)) {
//file exits
}
Simply use yourFile.exists();.
You need to point to the file and check if it exists.
File file = new File("C:\\file.txt");
if(!file.exists()){
System.out.println("file does not exist");
//Do all your stuff here
}
For my case what i had done is added this method:
public Boolean checkFile(){
Boolean myBool2 = false;
File file = getBaseContext().getFileStreamPath("current.xml");
if(file.exists()){
Toast.makeText(getApplicationContext(), "FileFound",
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(), "No file found",
Toast.LENGTH_LONG).show();
myBool2 = true;
}
return myBool2;
}
And it turns out that it worked! I just needed to get the context and then the filestreampath and it found the file.Thanks for everyone who has posted on this question, it really helped me understand what I was really trying to do!
What is the best way to find a directory with a specific name in Java? The directory that I am looking for can be located either in the current directory or one of its subdirectories.
In Java 8 via the streams API:
Optional<Path> hit = Files.walk(myPath)
.filter(file -> file.getFileName().equals(myName))
.findAny();
The #walk is lazy, so any short-circuiting terminal operation will optimize the IO required.
To walk the file tree, FileVisitor interface can be used.
Please see the tutorial. Please see Find sample codes also.
Your solution will include the use of File.listFiles(String)
java.io.File API reference
As you mentioned recursion should cater to this requirement
import java.io.File;
public class CheckFile {
private static boolean foundFolder = false;
public static void main(String[] args) {
File dir = new File("currentdirectory");
findDirectory(dir);
}
private static void findDirectory(File parentDirectory) {
if(foundFolder) {
return;
}
File[] files = parentDirectory.listFiles();
for (File file : files) {
if (file.isFile()) {
continue;
}
if (file.getName().equals("folderNameToFind")) {
foundFolder = true;
break;
}
if(file.isDirectory()) {
findDirectory(file);
}
}
}
}
Something like:
public static final File findIt(File rootDir, String fileName) {
File[] files = rootDir.listFiles();
List<File> directories = new ArrayList<File>(files.length);
for (File file : files) {
if (file.getName().equals(fileName)) {
return file;
} else if (file.isDirectory()) {
directories.add(file);
}
}
for (File directory : directories) {
File file = findIt(directory);
if (file != null) {
return file;
}
}
return null;
}
Divide and conquer? A naive approach: For every directory, you may start a task, it does the following:
list every directory
if the list contains a matching directory, prints and exit the application
start a task for every directory.
Or, you should use the concept of Recursively search the file until it found: Here is the Code:
String name; //to hold the search file name
public String listFolder(File dir) {
int flag;
File[] subDirs = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
System.out.println("File of Directory: " + dir.getAbsolutePath());
flag = Listfile(dir);
if (flag == 0) {
System.out.println("File Found in THe Directory: " + dir.getAbsolutePath());
Speak("File Found in THe Directory: !!" + dir.getAbsolutePath());
return dir.getAbsolutePath();
}
for (File folder : subDirs) {
listFolder(folder);
}
return null;
}
private int Listfile(File dir) {
boolean ch = false;
File[] files = dir.listFiles();
for (File file : files) {
Listfile(file);
if (file.getName().indexOf(name.toLowerCase()) != -1) {//check all in lower case
System.out.println(name + "Found Sucessfully!!");
ch = true;
}
}
if (ch) {
return 1;
} else {
return 0;
}
}
I want to filter files stored in my phone with the .apk extension. I have tried the below code but it filters files found only in sdcard/file.apk
but I want it to filter the file by searching into the sub directories of sdcard also.
For example if there is an apk file inside sdcard/download/mm.apk it should filter it and also if there is another file in sdcard/New Folder/ABC/cc.apk it should filter it too.
How can I do that? thank you for your help...
ExtFilter apkFilter = new ExtFilter("apk");
File file[] =Environment.getExternalStorageDirectory().listFiles(apkFilter);
Log.i("InstallApk","Filter applied. Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
Log.i("InstallApk",
"FileName:" + file[i].getName());
}
ArrayAdapter af=new ArrayAdapter<File>(this,android.R.layout.simple_list_item_1,android.R.id.text1,file);
ListView ll=(ListView) findViewById(R.id.mainListView1);
ll.setAdapter(af);
}
class ExtFilter implements
FilenameFilter {
String ext;
public ExtFilter(String ext) {
this.ext = "." + ext;
}
public boolean accept(File dir, String name)
{
return name.endsWith(ext);
}
}
You have to do it recursively. It is not enough to check for the extension, you must also verify that it is a regular file cos I can as well name a directory dir.apk. Verifying that it is a regular file is also not enough since one can name any file with any extension. Regardless, checking that it is a regular file should be enough without consideration of the intended action on these files.
public void someFunction() {
List<File> apkFiles = getApkFiles(Environment.getExternalStorageDirectory(), new ApkSearchFilter());
File file[] = apkFiles.toArray(new File[apkFiles.size()]);
Log.i("InstallApk", "Filter app\"lied. Size: " + file.length);
for (File aFile : file) {
Log.i("InstallApk", "FileName:" + aFile.getName());
}
}
List<File> getApkFiles(File file, ApkSearchFilter filter) {
if (filter.isApk(file))
return Collections.singletonList(file);
else if (filter.isDirectory(file)) {
LinkedList<File> files = new LinkedList<>();
for (File subFile : file.listFiles()) {
files.addAll(getApkFiles(subFile, filter));
}
return files;
} else return Collections.emptyList();
}
class ApkSearchFilter implements FileFilter {
boolean isApk(File file) {
return !file.isDirectory() && file.getName().matches(".*\\.apk");
}
boolean isDirectory(File file) {
return file.isDirectory();
}
#Override
public boolean accept(File file) {
return isDirectory(file) || isApk(file);
}
}
This is one in many way you can try, don't forget to add permission in manifest:
private List<String> ReadSDCard()
{
File f = new File("your path"); // Environment.getExternalStorageDirectory()
File[] files=f.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
String filePath = file.getPath();
if(filePath.endsWith(".apk"))
tFileList.add(filePath);
}
return tFileList;
}
I have a xml file that I'm getting its full path, and pass it to a function where I add a String to its name. However I'm not being able to use it (the initial fullpath) after adding the string. How can it be done, that after getting the fullpath in search(String dirName), and adding the string in lk(String fullpath), I can still use the path which is returned by search(String dirName).
public String search( String dirName)throws Exception{
String fullPath = null;
File dir = new File(dirName);
if ( dir.isDirectory() )
{
String[] list = dir.list(new FilenameFilter()
{
#Override
public boolean accept(File f, String s )
{
return s.endsWith(".xml");
}
});
if ( list.length > 0 )
{
fullPath = dirName+list[0];
lockFile(fullPath);
return fullPath;
}
}
return "";
}
public void lk( String fullPath) throws Exception {
File f = new File(fullPath);
String fileNameWithExt = f.getName();
try {
File newfile =new File(fileNameWithExt+".lock");
if(f.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
} catch (Exception e) {
e.printStackTrace();
}
}
try this
File originalFile = new File(<file parent path>, "myxmlfile");
File cloneFile = new File(originalFile.getParent(),
originalFile.getName()+"<anything_i_want_to_add>");
Files.copy(originalFile.toPath(),cloneFile.toPath());
//now your new file exist and you can use it
originalFile.delete();//you delete the original file
...
//after you are done with everything and you want the path back
Files.copy(cloneFile.toPath(),originalFile.toPath());
cloneFile.delete();
In your lock method, you are calling renameTo method. Because of that, the original filename is now gone, and is replaced by the new filename that ends with .lock.
The java.io.File class is not a file pointer but an object to hold a filename. Using a file object that still refers to an old filename will cause an error.
To answer your question: If you want the old filename after locking, you must use a different approach in locking your file. For example, MS Access locks their .accdb files by creating a lockfile with the same filename as the opened .accdb file.
You may use this code as a reference:
public boolean fileIsLocked(File file) {
File lock = new File(file.getAbsolutePath() + ".lock");
return lock.exists();
}
public void lockFile(File file) {
if (!fileIsLocked(file)) {
File lock = new File(file.getAbsolutePath() + ".lock");
lock.createNewFile();
lock.deleteOnExit(); // unlocks file on JVM exit
}
}
public void unlockFile(File file) {
if (fileIsLocked(file)) {
File lock = new File(file.getAbsolutePath() + ".lock");
lock.delete();
}
}
I am doing a simple application that loads and saves files in java. I am trying to port it over to Android and am having trouble getting it to see the file.
The file path I am currently using is
private static final String SAVE_FILE_PATH = "data/save";
Here is the function that loads the data from the file:
public void loadData() throws FileNotFoundException {
File file = new File(SAVE_FILE_PATH);
Scanner scanner;
if (file.exists()) {
scanner = new Scanner(new FileInputStream(file));
try {
while (scanner.hasNextLine()) {
allPlayers.add(new Player(scanner.nextLine()));
}
} finally {
scanner.close();
}
}
else {
System.out.println("No file found");
}
} finally {
scanner.close();
}
}
}
While getExternalStorageDirectory() gets you the path to the SD card, consider using Activity.getExternalFilesDir() which will return (and create if necessary) a directory that's nominally private to your application. It also has the advantage that it will be auto-deleted for you if the application is uninstalled. This is new in API 8, so you might not want to use it if you're supporting older devices.
Otherwise, you'll have to follow ρяσѕρєя K's advice. Don't forget to create the storage directory you want to use. My code typically looks like this:
/**
* Utility: Return the storage directory. Create it if necessary.
*/
public static File dataDir()
{
File sdcard = Environment.getExternalStorageDirectory();
if( sdcard == null || !sdcard.isDirectory() ) {
// TODO: warning popup
Log.w(TAG, "Storage card not found " + sdcard);
return null;
}
File datadir = new File(sdcard, "MyApplication");
if( !confirmDir(datadir) ) {
// TODO: warning popup
Log.w(TAG, "Unable to create " + datadir);
return null;
}
return datadir;
}
/**
* Create dir if necessary, return true on success
*/
public static final boolean confirmDir(File dir) {
if( dir.isDirectory() ) return true;
if( dir.exists() ) return false;
return dir.mkdirs();
}
Now use this to specify your save file:
File file = new File(dataDir(), "save");
Scanner scanner;
if (file.exists()) {
// etc.
}