Instantiating file object - java

I have this very basic question.
Does File file = new File("fileName"); actually create a file if one does not exist?
What happens if the file already exists in that location?
Are there any good tutorials you can point me to so I can read more about it?

No it does not. The File object represents an abstract notion of a file, which may exist, but doesn't need to. Note that the File object can also point to a directory (which may or may not exist).

Usually you can find out information about java in the api
http://docs.oracle.com/javase/7/docs/api/java/io/File.html

No, if you want to create an empty file, use createNewFile
File myFile = new File("test.txt");
myFile.createNewFile();

No, calling the objects constructor simply creates an instance of the File-Class.
Read the documentation:
File(File parent, String child):
Creates a new File instance from a parent abstract pathname and a child pathname string.
The call of the createNewFile()- Method writes the file to disk.
Atomically creates a new, empty file named by this abstract pathname
if and only if a file with this name does not yet exist.
You can simply check it by creating a File-object with a non existing file path and calling the File.exists(); method.
if (!file.exists()) {
//File does not exist
}

Related

Java FileReader vs File

I wanted to create a File/FileReader object to instantiate a Scanner object.
So, the text book had like this:
File file = new File("filename.txt");
However, our instructor was like, that is wrong, the correct way is:
FileReader file = new FileReader("filename.txt");
Both of them work. So, what's the difference between the two and which one's correct.
File(String name)
Creates a new File instance by converting the given pathname string
into an abstract pathname. If the given string is the empty string,
then the result is the empty abstract pathname.
FileWriter(String name)
Constructs a FileWriter object given a file name.
Basically, the difference is that only Instantiating a File won't allow you to write to it, while FileWriter does.
The constructor of FileWriter pass to OutputStreamWriter a new FileOutputStream which instantiate a File from the given name.
Note that a Scanner is used to read a File not to write in it.
Edit : To answer to your edited question where you changed FileWriter to FileReader, the main difference between a File and a FileReader is that File does not have a close method while a FileReader does and implement Closeable. Most of the methods offered by File object are meant to manipulate directly the file (check existence, delete, create, list all files from directory). As #Pshemo mentionned, a File is not to be seen as data, but simply as a path.
I recommend to read the File API and FileReader API.

File creation methods

When I use the following code to create file, it doesn't output a visible file.It doesn't give any exception. In the following code output is exist. That means file is actually there exist. But I can't visible. Actually what is going on here?
File file= new File("/folder/abc.txt");
if(file.exist)
System.out.println("exist");
File file= new File("/folder/abc.txt");
NEVER creates an actual file.
There are two ways to create a file:
Invoke the createNewFile() method on a File object. For example:
File file = new File("foo"); // no file yet
file.createNewFile(); // make a file, "foo" which
// is assigned to 'file'
Create a Writer or a Stream. Specifically, create a FileWriter, a PrintWriter,
or a FileOutputStream. Whenever you create an instance of one of these
classes, you automatically create a file, unless one already exists, for instance
File file = new File("foo"); // no file yet
PrintWriter pw = new PrintWriter(file); // make a PrintWriter object AND
// make a file, "foo" to which
// 'file' is assigned, AND assign
// 'pw' to the PrintWriter
It's a file abstraction class, this doesn't create any file yet. From documentation:
An abstract representation of file and directory pathnames.
You can do lot more than creating a new file, for example checking if such file or directory exist.
Creating a File instance does not create a File on your file system.
You need to call a method of that instance to create the file on the file system
File f = new File("/folder/myfile");
if(!f.exists){
f.createNewFile();
}
As per Java docs,
Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.
creates only a instance.
Actual file is created by using file.createNewFile();
You are just creating a java object, you need to use:
File file= new File("/folder/abc.txt");
file.createNewFile();
For good practice check if file exists if not then create new one.
File file= new File("/folder/abc.txt");
if(!file.exists())
file.createNewFile();
File file= new File("/folder/abc.txt");
creates java File object, not real file. to create real file call:
file.createNewFile();
or use Stream. For example:
FileOutputStream stream = new FileOutputStream(file);
Just because you create an instance of java.io.File class, that file on the filesystem won't be created instantly.
You have to take steps to actually create it. You will find information easily on this.

About File file = new File(path)

The Java.iO.File document says the following words about its constructor which takes the pathname:
public File(String pathname)
Creates a new File instance by converting the given pathname string
into an abstract pathname. If the given string is the empty string,
then the result is the empty abstract pathname.
But what if the pathname points to a file which is already existing?
File file = new File(PATH_TO_AN_EXISTING_FILE);
Does the above file instance represent a fresh new file (with the existing one be deleted?) Or does it represent the existing file ?
What the documentation says is that it will create a new File instance. This mean it will create a new instance in memory of the File class.
This object will point to a file on you file system. However, if the file exists, it will not create a new file.
I think the documentation is a little confusing: creating a new File object in Java does not mean creation of a new file in your file system. The File object is merely an abstract representation of file and directory pathname, it may or may not represent a real file on disk or on a network storage.
It is more or less equivalent to a String representing an address of something: when you write
String str = "1600 Pennsylvania Ave NW, Washington, DC 20500";
you create a string with an address of an existing building. There is no other connection between the string str that you created and The White House that happens to be located at that address.
The only difference between a File created with an existing path name and a file created with a non-existent path name is that the call of exists() on the former will return true, while the same call on the later would return false.
A File is not directly linked to an actual file on the file system. If the file exists, it will point to that file. If the file doesn't exist, it will not create it. exist() will return false.
This is a very confusingly named class.
A File object represents a file path, not an actual file. So when you create a File object you do not change anything on the filing system. Conceptually, it's no different to a String.
In java.nio, the class has been renamed to (the much more intuitive) Path.
The java.io.File class represents a path on some file system. It is not directly bound to a file. You are not opening a file when you create a File instance.
A File object is merely an object on the heap. Yes, it does have fields and methods that imply that this object represents a real file (or a directory: see the ambiguity?).
You can create File objects for files/directories that do not exist: nothing will happen to the file system; the File instances will be created. After all, a File is just a descriptor.
Furthermore, you can create several File objects with different paths (esp. when one is absolute and others are relative from different parent paths), but they will all point to the same file/directory when they are actually evaluated (by opening a file with In/OutputStream, Reader/Writer; when checking with exists() or creating: createFile(), createDirectory().
File f=new File("C://Existing_file")
above line indicates already existed file not the new one to be created file.
File class instance always refers to IO operations and also it always refers to already consisted file
By creating new instance
File f= new File("ABC.txt");
This new object of file will point to a file named ABC.txt in your system, if present. If the ABC.txt file is not there, then the file object simply does not point to any file.
When a file is stored in a computer. The information related to the file is also stored( you can check it in the properties by right clicking on file). These are those information that is about the file.
So the File class object does nothing except represents the information about the file.
The File class object only provides you with information about the file and the same is stated in its definition.

new File path in java without new object instance

Is it possible to change the filepath of the File class in java without creating a new instance?
File file = new File(System.getProperty("user.home")); <br>
System.out.println(file.getPath());
returns C:\Users\username
now I want to go to the parent directory. I thought I could use something like this
file.setPath(file.getParent());
but I have to use
file = new File(file.getParent());
any other way I can achieve the same? Or maybe I could create multiple instances, store them in an array and work with two objects (directories) at the same time?
From the javadocs:
Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.
So, no, you can't change a File instance. If you want a different value, you have to instantiate a new File.
Apparently you missed File.getParentFile():
file = file.getParentFile();

File Constructors Explanation

I was unable to understand the following file constructors.
public File(String parent, String child) and
public File(File parent, String child)
What do the parameters parent and child mean for the file? When can I use these? I have done few programs related to file but I have never used these. I usually use
public File(String pathname)
I have read Javadoc but I could not figure out when and how to use these constructors. Could someone please explain and give examples.
Explanation
The parent parameter is the parent directory of the child file name or relative file path.
Where parent is a File instance, it is a directory file. Where parent is a String, it's simply that directory in pathname terms.
Examples
Consider the following partial file system:
Documents
Homework
Classwork
Tests
Rather than declaring each new file with "Documents\Subdir", you can declare the Documents directory as a file, and use it as the parent File of the other File instances, like so:
File documents = new File("Documents");
File tests = new File("Documents/Tests"); // new File(String);
File homework = new File(documents, "Homework"); // new File(File, String)
File classwork = new File("Documents", "Classwork"); // new File(String, String)
Real-world application
In my experience, I've used applications that provide an API containing a method that returns the directory file in which third-party "plugins" are allowed to save/read files. Without the File(File, String) constructor, I would need to convert the directory file into an absolute path and append my target file to it.
In the following example, Environment.getProgramDirectory() returns the directory file in which permissions are granted.
File settingsFile = new File(Environment.getProgramDirectory(), "settings.txt");
Let's explain with some examples:
Assuming that you have the following structure:
/dir1
dir11
The constructor that you usually use new File("/dir1/dir11") is equivalent to
new File("/dir1", "dir11") (constructor taking 2 String as arguments)
and also equivalent to
new File(new File("/dir1"), "dir11") (constructor using a File as first argument).
"The parent abstract pathname is taken to denote a directory, and the child pathname string is taken to denote either a directory or a file. " As specified on the API
Parent will point to the Directory
Child will be its Contents..

Categories

Resources