Java, how to check the existence of file - java

I have this small code
File source;
if ( !source.exists() ) {
source = new File("instances/student"+student.getStudentID()+".data");
}
The problem is, source is not initialized. Since the whole point is to check if it exists, how do I avoid this?

Create a File object.
File source = new File(...);
What constructor you use depends on how you want to locate a file. A simple path String could be enough.
EDIT: just realized the source of your confusion may be that you think creating the File object will try to locate the file or create it on the file system. That's not the case. Just calling new File(...) won't check its existence or try to create it. A File object is simply an abstraction for a path in your file system. It could be a directory as well.

You can do:
File f = new File(somepathhere);
if ( !f.exists() ) {
f = new File("instances/student"+student.getStudentID()+".data");
}
Or you can check if f.isFile()

You seem to have a misunderstanding. Creating a File doesn't create a file on the file system. A File object only really represents a filename. If you want to see whether a file exists, create a File of the appropriate name and check exists().
But then if you want to overwrite or append to a file you don't even need all that. Just create a new FileOutputStream(...), with the append parameter set to true if you want to append. No need to check beforehand, in fact it is more than a waste of time.

Related

exists() does not work but getAbsolutePath() does work

I have the below code whereby I create a File type based on a pre-created file "test.brd" and also call the getAbsolutePath() method on this File, this all works correctly. However, when I run the exists() method, this is deemed as not existing.
When I debug, the status of the File is null and the path is also null, yet the getAbsolutePath() method works. I have debugged and it goes to the Security section of the exists() method.
Please see below:
File inputFile = new File("/Users/myname/Desktop/project_name/test.brd");
// The below works and returns the path
System.out.println(inputFile.getAbsolutePath());
if (inputFile.exists()) {
System.out.println("Exists");
}
else {
System.out.println("Invalid");
}
Even when I construct the file without the absolute path and just give the file name as a parameter (stored locally with Java file) the correct absolute path is provided.
Hope this makes sense. All I want to do is read a pre-created file into an Array, each character is an element in the array, I was intending on using scanner to read the file, but inputFile does not exist to be read.
The two methods are about different aspects of the file:
getAbsolutePath() is about file name. In a way, this is a "string manipulation method" completely separated from the actual file system
exists() is about the actual file. It checks whether or not the file is present in the file system at the location identified by the given path.
Note that getAbsolutePath() and other path manipulation methods of File must work even without the file or the folder being present in the actual file system. Otherwise, the API would not be able to support file creation, e.g. through createNewFile().
If you take a look at the javadoc, you can find the following sentence
Instances of this class may or may not denote an actual file-system object such as a file or a directory.
Proving that the instance in memory of a File object is not necessarily a real file or directory existing in the file system.
File inputFile = new File("/Users/myname/Desktop/project_name/test.brd");
The line above doesn't create a new File and hence it doesn't exists.
If you want to create a file you can use method inputFile.createNewFile().
The method getAbsolutePath() works on the inputFile object and is completely different from file creation.

Android get file using path (in String format)

My app needs to get an existing file for processing. Now I have the path of the file in String format, how can I get the File with it? Is it correct to do this:
File fileToSave = new File(dirOfTheFile);
Here dirOfTheFile is the path of the file. If I implement it in this way, will I get the existing file or the system will create another file for me?
That's what you want to do. If the file exists you'll get it. Otherwise you'll create it. You can check whether the file exists by calling fileToSave.exists() on it and act appropriately if it does not.
The new keyword is creating a File object in code, not necessarily a new file on the device.
I would caution you to not use hardcoded paths if you are for dirOfFile. For example, if you're accessing external storage, call Environment.getExternalStorageDirectory() instead of hardcoding /sdcard.
The File object is just a reference to a file (a wrapper around the path of the file); creating a new File object does not actually create or read the file; to do that, use FileInputStream to read, FileOutputStream to write, or the various File helper methods (like exists(), createNewFile(), etc.) for example to actually perform operations on the path in question. Note that, as others have pointed out, you should use one of the utilities provided by the system to locate directories on the internal or external storage, depending on where you want your files.
try this..
File fileToSave = new File(dirOfTheFile);
if(fileToSave.exists())
{
// the file exists. use it
} else {
// create file here
}
if parent folder is not there you may have to call fileToSave.getParentFile().mkdirs() to create parent folders

How to create a Path and a File that does not Exist in Java

This is the problem I have: If part or all of the path does not already exist, the server should create additional directories as necessary in the hierarchy and then create a new file as above.
Files.createDirectories(path);
That's what I am currently using, but it does not create the end file. For example is the path="/hello/test.html" it will create a directory called "hello" and one called "test.html", I want the test.html to be a file. How can I do that?
This is what I did to solve this "problem" or misuse of the libraries.
Files.createDirectories(path.getParent());
Files.createFile(path);
The first line will get the parent directory, so lets say this is what I want to create "/a/b/c/hello.txt", the parent directory will be "/a/b/c/".
The second like will create the file within that directory.
Have you looked at the javadoc? createDirectories only creates... directories. If you're intent on using Files.createDirectories, parse off the file name, call createDirectories passing only the path portion, then create a new file passing the entire path. Otherwise this is a better approach.
Files.createDirectories(path.substring(0, path.lastIndexOf(File.separator)+1));
File yourFile = new File(path);
you can parse the 'path' variable to isolate the file and the directory using delimiter as '/', and do File file = new File(parsedPath); This would work only when you know that you ALWAYS pass the file name at the end of it.
If you know when you are a) creating a directory b) creating a directory and file, you can pass the boolean variable that would describe if file needs to be created or not.

new a File object, namely create a file in disk?

when I new a File Object ,I found that there is not a file be create in disk,so I guess a File Obeject is not equal to a disk file, but when I write something to the File object through stream, I found the file be created in disk.
So, can I think like this, new File() - does not create a real file in disk, it is just an object in ram. But when you write something to the File through stream, for example:
FileWrite stream = new FileWrite(file);
stream.write(string);
..the stream will create a new file when the file does not exist (maybe function steam.write() does this?)?
How about File#createNewFile()? If you're using Java 7, you can also use Files.createFile(Path), as in this example from the Java tutorial.
FileWriter creates or truncates the file as required. The write put something in it. File is a file path name which may or may not exist. e.g. File.exists() is not always true and File.delete() can delete a file (i.e. the file no longer exists)

Does creation of new File(filename) object associate a process file descriptor with the object?

Does the following statement:
new File(filename);
associate a process file descriptor with the File object? Tried to search the same but without any success.
Ideally, it should not statically associate the file descriptor with the File object. Whenever, function calls are executed a file descriptor should get associated with the File Object for the period of time when the function call gets executed.
Any help appreciated.
There's no file descriptor, because new File(filename) does not open the file. It's just a easily manipulable representation of a path name.
File descriptors refer to open files. The fact that the file is not opened is not explicitly documented, but it follows from the principle of least surprise and from the fact that no exceptions are listed corresponding to failure to open the file.
No, new File(...) only is an object representing the filename, without even checking that there exists a file (or directory) with this name and/or path.
No. You can see this by examining the source of the File class yourself, from jdk 1.6.0_22:
public File(String pathname) {
if (pathname == null) {
throw new NullPointerException();
}
this.path = fs.normalize(pathname);
this.prefixLength = fs.prefixLength(this.path);
}
Since you can call the File constructor with a path that doesn't yet exist, and since File objects can represent non-existent Files, it wouldn't be possible to associate descriptors with it.

Categories