Android get file using path (in String format) - java

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

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.

Is using the File class in Java how you create a file?

I need some serious help with concepts. I have been given background context on the class, specifically this:
I just need to understand the purpose of this class? Can I create a text file (or any other type of file) with its constructors? Is this just for handling files, if so, what does that mean?
Any help whatsoever will be greatly appreciated!
Thank you
You could use the java.io.File to create a file on the file system:
File myFile = new File("myFile.txt");
myFile.createNewFile();
Note that invoking the constructor won't create the file on the file system. To create an empty file, the createNewFile() method has to be invoked.
The File simply represents a abstraction of the file location, not the file itself. It comes with operations on the file identified by the path: exists(), delete(), length(), etc.
What you probably want is to use the classes that allow you to write content to a file:
If you are to write text, you should use the Writer interface.
If you are to write binary content, you should use the OutputStream interface.
The classes FileWriter and FileOutputStream are, respectively, the ones that link the File and Writer/OutputStream concepts together. Those classes create the file on the file-system for you.
FileWriter myFileWriter = null;
File myFile = new File("myFile.txt");
try {
// file is created on the file-system here
myFileWriter = new FileWriter(myFile);
myFileWriter.write("hello");
} finally {
if (myFileWriter != null) {
myFileWriter.close();
}
}
You can create a file using the File.createNewFile method, or, if you are using Java 7 or newer, using the newer Files.createFile method.
The difference between the old File and the new Path classes is that the former mixed a reference to a path to a file on the filsystem and operations you can do on it, and the latter is just representing the path itself but allows you to query it and analyze its structure.

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)

Java, how to check the existence of file

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.

Categories