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

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.

Related

How to save a file with custom extension?

I am working on a project which creates a file with .bat extension.
In C++ it is possible by using
fstream myfile ("example.bat");
fstream<<"echo \"hello\" ";
But how can I do it in Java (JDK 8)?
I would suggest reading up on Java File IO. Whatever you want to call the file you're saving, you can. There aren't any custom extensions as opposed to normal extensions.
Additional Resource
I think this code does what you want. createFile will throw FileAlreadyExistsException if specified file already exists.
Path myBat = Paths.get("example.bat");
Files.createFile(myBat);
try( BufferedWriter reader = Files.newBufferedWriter(myBat) ) {
reader.append("hello");
}
Edit:
I think try-with-resources is needed here.

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

why new FileWriter("abc.txt") creates a new file and new File("abc.txt") does not?

new File("abc.txt") does not create actual file while new FileWriter("abc.txt") creates a file on disk. While going through source code i found that new FileWriter("abc.txt") eventually creates an object of file like new File()
Constructor of Class java.io.File does not create file on disk. It is just a abstraction over the file path. The file is created when you write to the file.
When you are creating FileWriter it calls constructor of FileOutputStream that calls a sequence of security checks and then invokes:
if (append) {
openAppend(name);
} else {
open(name);
}
Invocation of open() creates file on disk.
EDIT:
Here is how open() is defined:
/**
* Opens a file, with the specified name, for writing.
* #param name name of file to be opened
*/
private native void open(String name) throws FileNotFoundException;
I think file.createNewFile() creates the new file in actual.. please see following code for detal...
File file = new File("D:\\tables\\test.sql");
// if file does not exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
File doesn't always need to represent an actual file, it can be something you plan on creating, are guessing at the existence of, or something you've deleted as well.
From the JavaDoc for java.io.File:
An abstract representation of file and directory pathnames.
and
Instances of this class may or may not denote an actual file-system object such as a file or a directory.
In order to have the file actually be created, one needs to call createNEwFile(), whic according to the JavaDoc:
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.
The File object is simply a representation of a file's location (URL) in the system. You can call createNewFile() on a File object in order to write our a file assuming one with that name does not already exist in that location.
When FileWriter creates a new File object internally, this is not what causes the file to come into existence. That happens in other parts of the code. A File object is just a standard way to designate a file (or directory), whether or not it exists.
There are lots of reasons really, but:
File is used by many classes in java.io. FileReader, etc... FileWriter is a "convenience" class that uses File and it enables the programmer to be more productive. Some Classes just want a File object which points to a file location and then they operate on it as needed to support their processing. Other Classes might support a FileWriter because it will only be writing to a file and not reading. It also makes the API more strongly-typed.

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.

FileNotFound exception when trying to write to a file

OK, I'm feeling like this should be easy but am obviously missing something fundamental to file writing in Java. I have this:
File someFile = new File("someDirA/someDirB/someDirC/filename.txt");
and I just want to write to the file. However, while someDirA exists, someDirB (and therefore someDirC and filename.txt) do not exist. Doing this:
BufferedWriter writer = new BufferedWriter(new FileWriter(someFile));
throws a FileNotFoundException. Well, er, no kidding. I'm trying to create it after all. Do I need to break up the file path into components, create the directories and then create the file before instantiating the FileWriter object?
You have to create all the preceding directories first. And here is how to do it. You need to create a File object representing the path you want to exist and then call .mkdirs() on it. Then make sure you create the new file.
final File parent = new File("someDirA/someDirB/someDirC/");
if (!parent.mkdirs())
{
System.err.println("Could not create parent directories ");
}
final File someFile = new File(parent, "filename.txt");
someFile.createNewFile();
You can use the "mkdirs" method on the File class in Java. mkdirs will create your directory, and will create any non-existent parent directories if necessary.
http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html#mkdirs%28%29

Categories