Test path is accessible or not in java - java

I have a path i.e. "K:\user\abc.xml". I want to validate that path only that is valid or not, no need to create file at this location. I used file writer but it's create file. So please guide me what should I do?
Don't go with file please help me for path validation.

Create a File object:
File f = new File("K:\user\abc.xml");
and test if it exists:
if (f.exists()) {}
else {}

File f = new File("c:/temp");
if(f.exists()){
System.out.println("yes");
}else{
System.out.println("no");
}
This code will validate the given directory (or Path) is exists or not.
Here are the possible results:
if i have temp folder in c drive : yes
if i don't have temp folder in c drive : no
if you are writing to root directory like "C" path should "C:" (you should handle if user enter only "C" just append ":"
But, it purely dependent code for windows platform, you should think through platform independent.
Happy Codding.

Related

How does Java know a File is a file or a directory?

How does Java know:
new File("C:\Directory")
is a directory?
and
new File("C:\Directory\file.txt")
is a file?
I'm asking because I use this:
File f = new File(directory_path)
f.mkdirs()
and later on, I check if the file is a directory and it returns false.
if(f.isDirectory())
Do I have to set the file to be a directory or does Java figure it out based on the lack of .extension?
It consults the underlying file system which has an attribute that indicates whether a file is a directory or not.
From the code of File.isDirectory
return ((fs.getBooleanAttributes(this) & FileSystem.BA_DIRECTORY)
!= 0);

How check if the directory is exist? read to the end

Program should check if the directory is exist?? And if not, tell the user that there is no such folder.
I found many examples in which is explained how to check whether there is a file, but I need to know whether there is a directory? All methods
boolean x = context.getExternalFilesDir("/nicknameOfUser/").exists();
Toast.makeText(context, "ExternalFilesDir : " + x, Toast.LENGTH_SHORT).show();
isAbsolute(), isDirectory(), isFile(), create a new path to the files folder - nicknameOfUser I do not want to they were created, I just need to receive there is a directory or not ... I don't need create new folders...
How to do it? I think it is a question from regular, but I can't understand ...
When i launch app first time - in my filemanager no any file! But after i check .exists(); it create a path to the folder that i need a check... I DON'T NEED IT
To check if there is directory you have to use two conditions
File file = new File(filePath);
boolean isPresent = file.exists() && file.isDirectory();
returns true only if file exists and is directory.
You can ask for isDirectory() as follows :
File f = new File(Environment.getExternalStorageDirectory()+"/nicknameOfUser/");
if(f.isDirectory()) {
}
File file = new File("your path");
file.exists();
But after i check .exists(); it create a path to the folder that i need a check... I DON'T NEED IT
The problem is not the File.exists() call. It is the getExternalFilesDir call that is creating the directory. As the documentation states:
Unlike Environment.getExternalStoragePublicDirectory(), the directory returned here will be automatically created for you.
Eventually i found a solution. I begin to think it is impossible but all is ok
String fileDir = Environment.getExternalStorageDirectory().getAbsoluteFile() + "/nicknameOfUser/";
File file = new File(fileDir);
boolean x = file.exists();
This code work properly

Save a binary file in the same folder for every PC

I'm making a game that saves information into a binary file so that I can start at the point I left the game on the next use.
My problem is that it works fine on my PC because I chose a path that already existed to save the file, but once I run the game on another PC, I got an error saying the path of the file is invalid (because i doesn't exist yet, obviously).
Basically I'm using the File class to create the file and then the ObjectOutputStream and ObjectInputStream to read/write info.
Sorry for the noob question, I'm still pretty new to using files.
You must first check if the directory exists and if it does not exist then you must create it.
String folderPath = System.getProperty("user.home") + System.getProperty("file.separator") + "MyFolder";
File folder = new File(folderPath);
if(!folder.exists())
{
folder.mkdirs();
}
File saveFile = new File(folderPath, "fileName.ext");
Please note that the mkdirs() method is more useful in this case instead of the mkdir() method as it will create all non existing parent folders.
Hope this helps. Good luck and have fun programming!
Cheers,
Lofty
You are looking for File mkdirs()
Which will create all the directories necessary that are named in your path.
For example:
File dirs= new File("/this/path/does/not/exist/yet");
dirs.mkdir();
File file = new File(dirs, "myFile.txt");
Take in consideration that it may fail, due to proper file permissions.
My solution has been create a subdirectory within the user's home directory (System.getProperty("user.home")), like
File f = new File(System.getProperty("user.home") + "/CtrlAltDelData");
f.mkdir();
File mySaveFile = new File (f, "save1.txt");

Using environment variables in a Java File Path

I am writing a Java program to convert an XLS file to a CSV file for some Python parsers to act on them.
Everyday on my desktop (I'm using Ubuntu btw) I have a folder called "DFiles" inside which there is another folder called "20140705" (this folder is dynamicalle generated, tomorrow some other program deletes this folder and makes a new folder called 20140706 in its place). Inside this folder there is an xls file whose name is always "data.xls". I already have the code to convert it to CSV.
So here's my problem. Tomorrow my code my run on someone else's desktop(which is also Ubuntu). So when giving the path
input_document = new FileInputStream(new File("/home/local/TNA/srini/Desktop/DFiles/20140705/data.xls"+));
This unfortunately will work only today and only on my computer.
Ideally, I would like to do some thing like set the path to "$HOME/Desktop/Dfiles/2*/data.xls" as the file path. So how can I use bash env variables and wild cards in a file path in java?
You can get the value of an environment variable using System.getenv(...):
String homeDir = System.getenv("HOME");
String directory = homeDir + "/Desktop/DFiles/...";
Wildcards: That will not work. You can use listFiles() to list the files and directories inside a certain directory.
File dir = new File(homeDir + "/Desktop/DFiles";
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
System.out.println("Found subdirectory: " + f.getName());
} else {
System.out.println("Found file: " + f.getName());
}
}
You can write some code that recursively goes into the subdirectories and picks up any file of which the name ends with '.xls'.

How do I check if a file exists in Java?

How can I check whether a file exists, before opening it for reading in Java (the equivalent of Perl's -e $filename)?
The only similar question on SO deals with writing the file and was thus answered using FileWriter which is obviously not applicable here.
If possible I'd prefer a real API call returning true/false as opposed to some "Call API to open a file and catch when it throws an exception which you check for 'no file' in the text", but I can live with the latter.
Using java.io.File:
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}
I would recommend using isFile() instead of exists(). Most of the time you are looking to check if the path points to a file not only that it exists. Remember that exists() will return true if your path points to a directory.
new File("path/to/file.txt").isFile();
new File("C:/").exists() will return true but will not allow you to open and read from it as a file.
By using nio in Java SE 7,
import java.nio.file.*;
Path path = Paths.get(filePathString);
if (Files.exists(path)) {
// file exist
}
if (Files.notExists(path)) {
// file is not exist
}
If both exists and notExists return false, the existence of the file cannot be verified. (maybe no access right to this path)
You can check if path is a directory or regular file.
if (Files.isDirectory(path)) {
// path is directory
}
if (Files.isRegularFile(path)) {
// path is regular file
}
Please check this Java SE 7 tutorial.
Using Java 8:
if(Files.exists(Paths.get(filePathString))) {
// do something
}
File f = new File(filePathString);
This will not create a physical file. Will just create an object of the class File. To physically create a file you have to explicitly create it:
f.createNewFile();
So f.exists() can be used to check whether such a file exists or not.
f.isFile() && f.canRead()
There are multiple ways to achieve this.
In case of just for existence. It could be file or a directory.
new File("/path/to/file").exists();
Check for file
File f = new File("/path/to/file");
if(f.exists() && f.isFile()) {}
Check for Directory.
File f = new File("/path/to/file");
if(f.exists() && f.isDirectory()) {}
Java 7 way.
Path path = Paths.get("/path/to/file");
Files.exists(path) // Existence
Files.isDirectory(path) // is Directory
Files.isRegularFile(path) // Regular file
Files.isSymbolicLink(path) // Symbolic Link
Don't. Just catch the FileNotFoundException. The file system has to test whether the file exists anyway. There is no point in doing all that twice, and several reasons not to, such as:
double the code
the timing window problem whereby the file might exist when you test but not when you open, or vice versa, and
the fact that, as the existence of this question shows, you might make the wrong test and get the wrong answer.
Don't try to second-guess the system. It knows. And don't try to predict the future. In general the best way to test whether any resource is available is just to try to use it.
You can use the following: File.exists()
first hit for "java file exists" on google:
import java.io.*;
public class FileTest {
public static void main(String args[]) {
File f = new File(args[0]);
System.out.println(f + (f.exists()? " is found " : " is missing "));
}
}
For me a combination of the accepted answer by Sean A.O. Harney and the resulting comment by Cort3z seems to be the best solution.
Used the following snippet:
File f = new File(filePathString);
if(f.exists() && f.isFile()) {
//do something ...
}
Hope this could help someone.
I know I'm a bit late in this thread. However, here is my answer, valid since Java 7 and up.
The following snippet
if(Files.isRegularFile(Paths.get(pathToFile))) {
// do something
}
is perfectly satifactory, because method isRegularFile returns false if file does not exist. Therefore, no need to check if Files.exists(...).
Note that other parameters are options indicating how links should be handled. By default, symbolic links are followed.
From Java Oracle documentation
It's also well worth getting familiar with Commons FileUtils https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html
This has additional methods for managing files and often better than JDK.
Simple example with good coding practices and covering all cases :
private static void fetchIndexSafely(String url) throws FileAlreadyExistsException {
File f = new File(Constants.RFC_INDEX_LOCAL_NAME);
if (f.exists()) {
throw new FileAlreadyExistsException(f.getAbsolutePath());
} else {
try {
URL u = new URL(url);
FileUtils.copyURLToFile(u, f);
} catch (MalformedURLException ex) {
Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Reference and more examples at
https://zgrepcode.com/examples/java/java/nio/file/filealreadyexistsexception-implementations
Don't use File constructor with String.
This may not work!
Instead of this use URI:
File f = new File(new URI("file:///"+filePathString.replace('\\', '/')));
if(f.exists() && !f.isDirectory()) {
// to do
}
You can make it this way
import java.nio.file.Paths;
String file = "myfile.sss";
if(Paths.get(file).toFile().isFile()){
//...do somethinh
}
There is specific purpose to design these methods. We can't say use anyone to check file exist or not.
isFile(): Tests whether the file denoted by this abstract pathname is a normal file.
exists(): Tests whether the file or directory denoted by this abstract pathname exists.
docs.oracle.com
You must use the file class , create a file instance with the path of the file you want to check if existent . After that you must make sure that it is a file and not a directory . Afterwards you can call exist method on that file object referancing your file . Be aware that , file class in java is not representing a file . It actually represents a directory path or a file path , and the abstract path it represents does not have to exist physically on your computer . It is just a representation , that`s why , you can enter a path of a file as an argument while creating file object , and then check if that folder in that path does really exist , with the exists() method .
If spring framework is used and the file path starts with classpath:
public static boolean fileExists(String sFileName) {
if (sFileName.startsWith("classpath:")) {
String path = sFileName.substring("classpath:".length());
ClassLoader cl = ClassUtils.getDefaultClassLoader();
URL url = cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path);
return (url != null);
} else {
Path path = Paths.get(sFileName);
return Files.exists(path);
}
}

Categories