checking if file exists in a specific directory - java

I am trying to check for a specific file in a given directory. I don't want the code but I want to fix the one I have. The only difference in this question, is that I look for files with an extension .MOD.
I have the code ready:-
public static int checkExists(String directory, String file) {
File dir = new File(directory);
File[] dir_contents = dir.listFiles();
String temp = file + ".MOD";
boolean check = new File(temp).exists();
System.out.println("Check"+check); // -->always says false
for(int i = 0; i<dir_contents.length;i++) {
if(dir_contents[i].getName() == (file + ".MOD"))
return Constants.FILE_EXISTS;
}
return Constants.FILE_DOES_NOT_EXIST;
}
But for some reasons, it does not work. I don't understand why, can anybody find any bug here?

Do you expect temp.MOD file to be in the current directory (the directory from which you run your application), or you want it to be in the "directory" folder? In the latter case, try creating the file this way:
boolean check = new File(directory, temp).exists();
Also check for the file permissions, because it will fail on permission errors as well. Case sensitivily might also be the cause of the issue as Spaeth mentioned.

This is where you have the bug.
String temp = file + ".MOD";
And
if(dir_contents[i].getName() == (file + ".MOD"))
The code boolean check = new File(temp).exists(); will check for the file in the current directory not in the required directory.
String dirName="/home/demo";
File dir = new File(dirName);
File[] dir_contents = dir.listFiles();
String temp = dirName+"/"+"README" + ".MOD";
boolean check = new File(temp).exists();
System.out.println("Check" + check); // -->always says false
for (int i = 0; i < dir_contents.length; i++) {
if (dir_contents[i].getName().equals("README" + ".MOD"))
return Constants.FILE_EXISTS;
}
return Constants.FILE_DOES_NOT_EXIST;

Try this..............
File f = new File("./file_name");
if(f.exists()){
System.out.println("success");
}
else{
System.out.println("fail");
}

Related

Validate Excel file is downloaded in Selenium Web driver Java

I'm able to download excel file by clicking Download button which comes under DOM ,
after that i want verify downloaded file is same one.
AUTO IT is not allowed in project.
I have tried below code for verification on local but if i will push this code to repo.
then user path will get change and code will fail.
`String filepath = "C:User\\Dhananjay\\Downloads";
String fileName = "report.xlsx"
File targetFile = new File(fileName,filePath);
if(! targetFile.exists())'
{
system.out.println("File is verified")`
}else{
system.out.println("file not downloaded")
}'
String userProfile = System.getProperty("user.home"); returns %USERPROFILE% variable.
So you can use String filepath = System.getProperty("user.home") + "\\Downloads";
Works even on Linux.
I have found way to validate on local path and it's generic one
File folder = new File(System.getProperty("user.home") +\\Downloads);
File[] listOfFiles = folder.listFiles();
boolean found = false;
File f = null;
for (File listOfFile : listOfFiles) {
if (listOfFile.isFile()) {
String fileName = listOfFile.getName();
System.out.println("File " + listOfFile.getName());
if (fileName.matches("5MB.zip")) {
f = new File(fileName);
found = true;
}
}
}
Assert.assertTrue("Downloaded document is not found",found );
f.deleteOnExit();

Change files names in parent and child directories

I am a beginner in Java trying to work with Files and Directories. I wanted to create a program where I could change file names automatically while searching through all the child directories for file names that are not valid. I am actually trying to load a huge amount of files on to a server but the server settings do not allow file names containing special characters. To start with I was able to write the code where if I pass the path to a directory it renames all the files with invalid names in that directory:
public class reNaming {
public static String baseLoc = "C:/Users/Developer/Desktop/.../Data Cleanup";
public static void main(String[] args) {
//LinkedList<File> fileList = new LinkedList<File>();
File obj = new File(baseLoc);
int count = 0;
for (File file: obj.listFiles())
{
String origName = file.getName();
if (origName.contains("&") || origName.contains("#") || origName.contains("#"))
{
System.out.println("Original name: "+origName);
origName = origName.replaceAll("&", "_and_");
origName = origName.replaceAll("#", "_at_");
String newName = origName.replaceAll("#", "_");
System.out.println("New Name: "+newName);
String newLoc = baseLoc+"/"+newName;
File newFile = new File(newLoc);
System.out.println(file.renameTo(newFile));
count++;
}
}
}
}
Now I want to do the same but only this time I want all the files to be reNamed even in the child directories. Can somebody please guide me how I can achieve that?
Recursion is your friend
/**Removes 'invalid' characters (&,#,#) from pathnames in the given folder, and subfolders, and returns the number of files renamed*/
public int renameDirectory(File base){
//LinkedList<File> fileList = new LinkedList<File>();
int count=0;//count the renamed files in this directory + its sub. You wanted to do this?
//Process each file in this folder.
for (File file: base.listFiles()){
String origName = file.getName();
File resultFile=file;
if (origName.contains("&") || origName.contains("#") || origName.contains("#")){
//I would replace the if statement with origName.matches(".*[&##].*") or similar, shorter but more error prone.
System.out.println("Original name: "+origName);
origName = origName.replaceAll("&", "_and_");
origName = origName.replaceAll("#", "_at_");
String newName = origName.replaceAll("#", "_");
System.out.println("New Name: "+newName);
String newLoc = baseLoc+File.separator+newName;//having "/" hardcoded is not cross-platform.
File newFile = new File(newLoc);
System.out.println(file.renameTo(newFile));
count++;
resultFile=newFile;//not sure if you could do file=newFile, tired
}
//if this 'file' in the base folder is a directory, process the directory
if(resultFile.isDirectory()){//or similar function
count+=renameDirectory(resultFile);
}
}
return count;
}
Move the code you have to a utility method (e.g. public void renameAll(File f){}). Have a condition that checks if the file is a directory and recursively call your method with it's contents. After that do what you are currently doing.
public void renameAll(File[] files){
for(File f: files){
if(f.isDirectory){
renameAll(f.listFiles());
}
rename(f);
}
}
public void rename(File f){ }

Java mkdir + mkdirs always return false

I'm trying to create a new dir in Java but it doesn't work. I'm wondering why because I tried mkdir() first and then I tried mkdirs() which is supposed to create unexistant directories.
I wrote :
boolean status = new File("C:\\Users\\Hito\\Desktop\\test").mkdir();
// status = false
then I wrote
boolean status = new File("C:\\Users\\Hito\\Desktop\\test").mkdirs();
// status still = false.
A clue ?
This is faster to type, and does not need double slashes:
boolean status = new File("C:/Users/Hito/Desktop/test").mkdir();
if you still get errors, check if the parent directory exists, and if file is writeable.
String path = "C:/Users/Hito/Desktop/";
File file = new File(path);
If (!path.exists()) {
System.out.println("path does not exist:" + path);
} else {
File dir = new File(path + "test");
if (!dir.canWrite()) {
System.out.println("dir not writeable" + path + "test");
}
}
File file = new File("C:/Users/Hito/Desktop/test");
file.mkdirs();
file.createNewFile();
Check your permissions
Try it:
boolean status = new File("C:\\Users\\Hito\\Desktop\\test").canWrite();
It's kinda strange because I used the windows search and I could find my directory BUT it's not located at :
C:\Users\Hito\Desktop
but at :
C:\Users\Hito\Desktop\Dropbox\Stage\Applic_WIDT
which is the directory containing my application.

What are fields i should change for my codes to suit my own codes?

What are the fields in the example (below) that I should change in relation to my mainActivity.java file? Sorry I'm kinda new in android/java therefore I don't really know what fields to change to suit my existing code. Can someone help?
My mainActivity.java file
File dirlist = new File(Environment.getExternalStorageDirectory() + "/VideoList");
if(!(dirlist.exists()))
dirlist.mkdir();
File TempFile = new File(Environment.getExternalStorageDirectory() + "/VideoList", dateFormat.format(date) + fileFormat);
This is an example I found but I do not know which fields I should change here to suit my code above. I want to preserve its existing function of calculating the size of the directory.
private static long dirSize(File dir) {
long result = 0;
Stack<File> dirlist= new Stack<File>();
dirlist.clear();
dirlist.push(dir);
while(!dirlist.isEmpty())
{
File dirCurrent = dirlist.pop();
File[] fileList = dirCurrent.listFiles();
for (int i = 0; i < fileList.length; i++) {
if(fileList[i].isDirectory())
dirlist.push(fileList[i]);
else
result += fileList[i].length();
}
}
return result;
}
I don't actually get what do you want, but if you want to get the size of a directory it is:
File dir = new File("c:/dir");
if (!dir.isDirectory()) {
dir.mkdirs();
}
long dirLength = dir.length();
System.out.println(dirLength);

How do i incorporate these code below into my current existing codes?

I was task to allocate only 1GB of space to store my videos in a particular file directory where it is going to auto-delete the oldest video file in that directory once its about to reach/hit 1GB?
And i eventually found these code but i was left with a problem on how to incorporate these example 1/2 codes into my current existing mainActivity.java file because of the differences in names like "dirlist,tempFile" compared with other examples 1/2 given to perform the task of size checking and deleting.
Sorry i'm kinna new in android/java therefore i don't really know what "fields" to change to suit my current coding needs? Can someone help on how am i going to complie these set of codes into a single set of code which perform the above mention functions??
My Current existing mainActivity.java
File dirlist = new File(Environment.getExternalStorageDirectory() + "/VideoList");
if(!(dirlist.exists()))
dirlist.mkdir();
File TempFile = new File(Environment.getExternalStorageDirectory()
+ "/VideoList", dateFormat.format(date) + fileFormat);
mediaRecorder.setOutputFile(TempFile.getPath());
(Example 1) code for summing up directory file size in a given folder..
private static long dirSize(File dir) {
long result = 0;
Stack<File> dirlist= new Stack<File>();
dirlist.clear();
dirlist.push(dir);
while(!dirlist.isEmpty())
{
File dirCurrent = dirlist.pop();
File[] fileList = dirCurrent.listFiles();
for (int i = 0; i < fileList.length; i++) {
if(fileList[i].isDirectory())
dirlist.push(fileList[i]);
else
result += fileList[i].length();
}
}
return result;
}
(Example 2) set of code for getting all the files in an array, and sorts them depending on their modified/created date. Then the first file in your array is your oldest file and delete it.
// no idea what are the parameters i should enter
// here for my case in mainActivity??
File directory = new File((**String for absolute path to directory**);
File[] files = directory.listFiles();
Arrays.sort(files, new Comparator<File>() {
#Override
public int compare(File f1, File f2)
{
return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
}});
file[0].delete();
This is a reference to your previous question: How do I put a capped maximum directory storage space in SD?. In the future, you should keep discussions about the same topic in the same question, rather than create 2 new identical questions.
In your Activity class lets say you define these 2 methods:
private void deleteOldestFile(File directory)
{
File[] files = directory.listFiles();
Arrays.sort(files, new Comparator<File>() {
#Override
public int compare(File f1, File f2)
{
return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
}});
files[0].delete();
}
private static long dirSize(File dir) {
long result = 0;
File[] fileList = dir.listFiles();
for(int i = 0; i < fileList.length; i++) {
if(fileList[i].isDirectory()) {
result += dirSize(fileList [i]);
} else {
// Sum the file size in bytes
result += fileList[i].length();
}
}
return result;
}
You can now do this with your code:
File dirlist = new File(Environment.getExternalStorageDirectory() + "/VideoList");
if(!(dirlist.exists()))
dirlist.mkdir();
Long directorySize = dirSize(dirlist);
if (directorySize > 1073741824) // this is 1GB in bytes
{
deleteOldestFile(dirlist);
}
File TempFile = new File(Environment.getExternalStorageDirectory()
+ "/VideoList", dateFormat.format(date) + fileFormat);
mediaRecorder.setOutputFile(TempFile.getPath());
So before setting the output file in that folder, it checks if the folder is > 1GB, and if so, deletes the oldest file first.
To be honest though, deleting the oldest file may not necessarily make the directory size < 1GB, so i would use a while loop to ensure that it is < 1GB like so:
while (directorySize > 1073741824)
{
deleteOldestFile(dirlist);
direcotrySize = dirSize(dirlist);
}

Categories

Resources