File Exists in Java? - java

I trying to check whether a file exists at given directory location.
File seacrhFile = new File("D:/input", contract.conf);
if (seacrhFile.exists()) {
returnFile = seacrhFile;
} else {
System.out.println("No such file exists");
}
reutrn returnFile;
This is working in D:/input directory scenario, but if I Change the directory location to src/test/resources/input folder then I am getting No such file exists, eventhough the file exists.

If you want to have access to
src/test/resources/input
you probably should use
System.getProperty("user.dir") + File.separator + "src/test/resources/input"
because the system-property "user.dir" points to the projectlocation.
If you just use "src/test/resources/input" you will get your mentioned exception, because the File Object don't "start" at the project location. So you have to specify it manually.
Nevertheless it's better to use the getResource-Method to retrieve different resources within your project, because if you run your project with the jar-File you need to tweak around to get "user.dir" to work correctly.
Just a basic example for the Classloader:
ClassLoader.getSystemClassLoader().getResource("test/resources/input");
This returns an URL-Object, with this object you can get the File-Object using ...
URL filePath = ClassLoader.getSystemClassLoader().getResource("test/resources/input");
File file = new File( filePath.toURI() );

Remove the src and try it again .

Related

How to check if a file retrieved from the ftp site exists in the local folder in java using talend?

I am using FtpGet to extract or retrieve a file from the ftp and loading into the database and before that i am storing in a local folder.
So before i use tfilecopy to the local Folder i would like to perform a check wherein if the file already exists in the local folder skip or ignore the next steps,if they dont exist then only write (tfilecopy) to the local folder.
So basically i want to iterate through the list of files in the local folder based on the one i am retrieving using
GlobalMap variables:dynamically and check if that file exists or not amongst the list of all the other files in that folder and perform the action.
I Have created this in talend,i could either check the database to see if the file exists or directly check the local folder where there is a copy of the ftp files(if the same file already exists) skip the process.
Only if it does not exist write to the local folder.
Which is the best approach either to scan it in the internal folders(although there maybe sub-folders as well) by writing a tjava code
Or use database script to query and only if the filename does not exist in the table,copy that file onto a target folder and write to a db table.
So primarily i am iterating through the current file from tfilelist3 and checking if they exist in tfilelist2 component using TJAVA and tfilecopy only if the file retrieved does not exist in tfilelist_2
TJAVA:
String path =((String)globalMap.get("tFileList_2_CURRENT_FILEDIRECTORY"));
System.out.println("PRINTING PATH in string: " +path);
Path filepath=Paths.get(path);
System.out.println("PRINTING PATH in PATH: " +filepath);
String fileName =((String)globalMap.get("tFileList_3_CURRENT_FILE"));
System.out.println("PRINTING FILENAME IN STRING: " +fileName);
File file = new File(fileName);
System.out.println("File is " +file);
//File f = new File(path);
if(file.exists())
{
System.out.println("Filename: "+file); //+ path.toString());
System.out.println("Exist in location!");
// System.out.println("File EXIST " +f);
} else
{
System.out.println("Filename: "+file); //+ path.toString());
System.out.println("Does not exist in location!");
}
I kinda made it little complex and i am lost now,would be great if someone could fix the remaining part and make it work,i cant seem to find a way through this maze now !
I had tried different versions and none of the seem to produce the result that i am looking for?
So file.exists() only checks for the specific file in the current directory,so what if i need to check in a different directory,how do i pass the arguments?
Approach 2 :
You can create a java routine eg:
findFile("fileName","FilePath")
Invoke the routine for each file by passing the fileName and filePath as parameters.
Did you check tFileExist component ? It seems that it could be useful (only parameter is folder+filename you want to check ).

Unable to check if file exists or not in web project

I have a pdf file in my web project at the below location :
"static/Downloadables/20/Home_insurance_booklet.pdf "
"static" is present in the WebContent. The context root of the project is "pas".
In one of the jsp, I need to check if the file Home_insurance_booklet.pdf exists or not. I tried in many ways but unable to succeed. Below is the code I have used.
String filePath = request.getContextPath()+"/static/Downloadables/20/Home_insurance_booklet.pdf";
if(new File(filePath.toString()).exists()) {
------
}
Through the file exists, the condition is returning false. How to check if the file exists or not w.r.t to certain location in the root of the web project ?
Edit:
File path displayed is
/pas/static/Downloadables/20/Home_insurance_booklet.pdf
Try the following:
String path = getServletContext().getRealPath("/static/Downloadables/20/Home_insurance_booklet.pdf")
File file = new File(path)
if (file.exists()) {
// Success
}
And here is the API-Doc of getRealPath():
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)
Use
ServletContext context = request.getServletContext();
StringBuilder finalPathToFile = new StringBuilder(context.getRealPath("/"));
The ServletContext#getRealPath() converts a web content path (the path in the expanded WAR folder structure on the server's disk file system) to an absolute disk file system path.
The "/" represents the web content root.
After that append in this way :
finalPathToFile.append("/static/Downloadables/20/Home_insurance_booklet.pdf");
Then use
if(new File(finalPathToFile.toString()).exists()) {
---------------------
doWhateverYouWantToDo
---------------------
}
check whether file is loaded in the project or not. and then try for absolute path first of the file in your code then try for relative path.
You have to use a file system based URL instead of relative web based URL.

relative file path not working in Java

After reading that is it possible to create a relative filepath name using "../" I tried it out.
I have a relative path for a file set like this:
String dir = ".." + File.separator + "web" + File.separator + "main";
But when I try setting the file with the code below, I get a FileNotFoundException.
File nFile= new File(dir + File.separator + "new.txt");
Why is this?
nFile prints: "C:\dev\app\build\..\web\main"
and
("") file prints "C:\dev\app\build"
According to your outputs, after you enter build you go up 1 time with .. back to app and expect web to be there (in the same level as build). Make sure that the directory C:\dev\app\web\main exists.
You could use exists() to check whether the directory dir exist, if not create it using mkdirs()
Sample code:
File parent = new File(dir);
if(! parent.exists()) {
parents.mkdirs();
}
File nFile = new File(parent, "new.txt");
Note that it is possible that the file denoted by parent may already exist but is not a directory, in witch case it would not be possible to use it a s parent. The above code does not handle this case.
Why wont you take the Env-Varable "user.dir"?
It returns you the path, in which the application was started from.
System.getProperty(user.dir)+File.separator+"main"+File.separator+[and so on]

Specifying a relative path in File in Java

I'm uploading images using Spring and Hibernate. I'm saving images on the server as follows.
File savedFile = new File("E:/Project/SpringHibernet/MultiplexTicketBooking/web/images/" + itemName);
item.write(savedFile);
Where itemName is the image file name after parsing the request (enctype="multipart/form-data"). I however need to mention the relative path in the constructor of File. Something like the one shown below.
File savedFile = new File("MultiplexTicketBooking/web/images/" + itemName);
item.write(savedFile);
But it doesn't work throwing the FileNotFoundException. Is there a way to specify a relative path with File in Java?
Try printing the working directory from your program.
String curDir = System.getProperty("user.dir");
Gets you that directory. Then check if the directories MultiplexTicketBooking/web/images/ exist in that directory.
Can't count the number of times I've been mistaken about my current dir and spent some time looking for a file I wrote to...
It seems the server should offer functionality as might be seen in the methods getContextPath() or getRealPath(String). It would be common to build paths based on those types of server related and reproducible paths. Do not use something like user.dir which makes almost no sense in a server.
Update
ServletContext sc=request.getSession().getServletContext();
File savedFile = new File(sc.getRealPath("images")+"\\" + itemName);
Rather than use "\\" I'd tend to replace that with the following which will cause the correct file separator to be used for each platform. Retain cross-platform compatibility for when the client decides to swap the MS/ISS based server out for a Linux/Tomcat stack. ;)
File savedFile = new File(sc.getRealPath("images"), itemName); //note the ','
See File(String,String) for details.
You could get the path of your project using the following -
File file = new File("");
System.out.println("" + file.getAbsolutePath());
So you could have a constants or a properties file where you could define your path which is MultiplexTicketBooking/web/images/ after the relative path.
You could append your path with the path you get from file.getAbsolutePath() and that will be the real path of the file. - file.getAbsolutePath() + MultiplexTicketBooking/web/images/.
Make sure the folders after the Project path i.e. MultiplexTicketBooking/web/images/ exist.
You can specify the path both absolute and relative with File. The FileNotFoundException can be thrown because the folder might be there. Try using the mkdirs() method first in to create the folder structure you need in order to save your file where you're trying to save it.

Find Path During Runtime To Delete File

The code basically allows the user to input the name of the file that they would like to delete which is held in the variable 'catName' and then the following code is executed to try and find the path of the file and delete it. However, it doesn't seem to work, as it won't delete the file this way. Is does however delete the file if I input the whole path.
File file = new File(catName + ".txt");
String path = file.getCanonicalPath();
File filePath = new File(path);
filePath.delete();
If you're deleting files in the same directory that the program is executing in, you don't need specify a path, but if it's not in the same directory that your program is running in and you're expecting the program to know what directory your file is in, that's not going to happen.
Regarding your code above: the following examples all do the same thing. Let's assume your path is /home/kim/files and that's where you executed the program.
// deletes /home/kim/files/somefile.txt
boolean result = new File("somefile.txt").delete();
// deletes /home/kim/files/somefile.txt
File f = new File("somefile.txt");
boolean result = new File(f.getCanonicalPath()).delete();
// deletes /home/kim/files/somefile.txt
String execPath = System.getProperty("user.dir");
File f = new File(execPath+"/somefile.txt");
f.delete();
In other words, you'll need to specify the path where the deletable files are located. If they are located in different and changing locations, then you'll have to implement a search of your filesystem for the file, which could take a long time if it's a big filesystem. Here's an article on how to implement that.
Depending on what file you want to delete, and where it is stored, chances are that you are expecting Java to magically find the file.
String catName = 'test'
File file = new File(catName + '.txt');
If the program is running in say C:\TestProg\, then the File object is pointing to a file in the location C:\TestProg\test.txt. Since the file object is more of just a helper, it has no issues with pointing to a non-existent file (File can be used to create new files).
If you are trying to delete a file that is in a specific location, then you need to prepend the folder name to the file path, either canonically, or relative to the execution location.
String catName = 'test'
File file = new File('myfiles\\'+ catName +'.txt');
Now file is looking in C:\TestProg\myfiles\test.txt.
If you want to find that file anywhere, then you need a recursive search algorithm, that will traverse the filesystem.
The piece of code that you provided could be compacted to this:
boolean success = new File(catName + ".txt").delete();
The success variable will be true if the deletion was successful. If you do not provide the full absolute path (e.g. C:\Temp\test for the C:\Temp\test.txt file), your program will assume that the path is relative to its current working directory - typically the directory from where it was launched.
You should either provide an absolute path, or a path relative to the current directory. Your program will not try to find the file to delete anywhere else.

Categories