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.
Related
I have a CSV file inside a folder that's inside the source folder but I can't get to it.
I got it to work with what I've found on internet:
URL url = getClass().getResource("/csv/recetas.csv");
File file = new File(url.getPath());
FileReader fileReader = new FileReader(file);
CSVReader csvReader = new CSVReader(fileReader, ',', '"', 1);
but it only works when I run it in the IDE. When I build the jar and try to run it, the FileReader can't find the file, it doesn't throw error for URL or File.
Here is my project folder so you can understand me. Thanks.
InputStream in = getClass().getResourceAsStream("/csv/recetas.csv");
InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
CSVReader(reader, ',', '"', 1);
Resources are class path "files" possibly packed in a jar. They are not File, and are read-only.
Also for compatibility, give the charset explicitly.
The getClass().getResource() uses the class loader to load the resource. This means that your csv file will not be visible unless it is in the classpath.
Looking at your code and your problem again, getClass().getResource() seems redundant to me as the constructor of File(...) accepts a file path depicted as String.
See:
https://docs.oracle.com/javase/7/docs/api/java/io/File.html
Quote:
File(String pathname) Creates a new File instance by converting the
given pathname string into an abstract pathname.
To make your program more versatile I would recommend you to avoid hardcoding the file path as the csv file can be anywhere within the file system and it may not always be called recetas.csv.
What people typically would do is to make the java program accept an option like --csv. Then let the user specify the filepath and your code will just be new File(theSpecifiedPath).
I am new to programming, I need help in understanding the difference between 2 ways of creating a fileinputstream object for reading files. I have seen examples on internet, some have used first one and others second one. I am confused which is better and why?
FileInputStream file = new FileInputStream(new File(path));
FileInputStream file = new FileInputStream(path);
Both are fine. The second one calls the first implicitly.
public FileInputStream(String name) throws FileNotFoundException {
this(name != null ? new File(name) : null);
}
If you have a reference to the file which should be read, use the former. Else, you should probably use the latter (if you only have the path).
Don't use either in 2015. Use Files.newInputStream() instead. In a try-with-resources statement, at that:
final Path path = Paths.get("path/to/file");
try (
final InputStream in = Files.newInputStream(path);
) {
// do stuff with "in"
}
More generally, don't use anything File in new code in 2015 if you can avoid it. JSR 203, aka NIO2, aka java.nio.file, is incomparably better than java.io.File. And it has been there since 2011.
The FileInputStream Class has three constructors. Described in the official documentation:
FileInputStream(File file)
Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.
FileInputStream(String name)
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.
FileInputStream(FileDescriptor fdObj)
Creates a FileInputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system.
As you see here there is no real difference.
Actually they both have the same way to open a file. The first constructor calls
SecurityManager.checkRead(File.getPath())
And the second one uses the same checkRead() as
SecurityManager.checkRead(name)
if you want use
FileInputStream file = new FileInputStream(new File(path));
for create FileInputStream need more time, if I don't mistake, because this constructor doing some checks with security manager
There is not much difference between the two , as
FileInputStream file = new FileInputStream(path)
implicitly calling other.
public FileInputStream(String name) throws FileNotFoundException {
this(name != null ? new File(name) : null);
}
But to make better use of two available constructors, we can use constructor taking File argument when there is already a File object so we will be avoiding creation of another file object which will be created implicitly If we are using another constructor
Secondly, It is better to create FileinputStream object only after checking the existence of file which can be checked by using file.exists() in that case we can avoid FileNotFoundException.
is there a way to open a directory stream in Java like in C? I need a FileDescriptor of an opened directory. Well, actually just the number of the fd.
I try to implement a checkpoint/restore functionality in Java with the help of CRIU link. To do this, I need to deploy a RPC call to the CRIU service. There I have to provide the integer value of the FD of an already opened directory, where the image files of the process will be stored.
Thank you in advance!
is there a way to open a directory stream in Java like in C?
No there isn't. Not without resorting to native code.
If you want to "read" a directory in (pure) Java, you can do it using one of the following:
File.list() - gives you the names of the directory entries as strings.
File.list(FilenameFilter) - ditto, but only directory entries that match are returned.
File.listFiles() - like list() but returning File objects.
etcetera
Files.newDirectoryStream(Path) gives you an iterator for the Path objects for the entries in a directory.
The last one could be "close" to what you are trying to achieve, but it does not entail application code getting hold of a file descriptor for a directory, or the application doing a low-level "read" on the directory.
You don't need FD in Java. All you need is a reference to that file which you can simply acquire using File file = new File("PathToYourFile");
To read/write you have Streams in Java. You can use
BufferedReader fileReader = new BufferedReader(new FileReader(new File("myFile.txt")));
PrintWriter fileWriter = new PrintWriter(new FileWriter(new File("myFile.txt")));
Even directory is a file. You can use isDirectory() on file object to check if it is a directory or a file.
private FileDescriptor openFile(String path)
throws FileNotFoundException, IOException {
File file = new File(path);
FileOutputStream fos = new FileOutputStream(file);
// remember th 'fos' reference somewhere for later closing it
fos.write((new Date() + " Beginning of process...").getBytes());
return fos.getFD();
}
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.
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
}