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.
Related
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.
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();
}
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
}
I'm reading a bunch of files from an FTP. Then I need to unzip those files and write them to a fileshare.
I don't want to write the files first and then read them back and unzip them. I want to do it all in one go. Is that possible?
This is my code
FTPClient fileclient = new FTPClient();
..
ByteArrayOutputStream out = new ByteArrayOutputStream();
fileclient.retrieveFile(filename, out);
??????? //How do I get my out-stream into a File-object?
File file = new File(?);
ZipFile zipFile = new ZipFile(file,ZipFile.OPEN_READ);
Any ideas?
You should use a ZipInputStream wrapped around the InputStream returned from FTPClient's retrieveFileStream(String remote).
You don't need to create the File object.
If you want to save the file you should pipe the stream directly into a ZipOutputStream
ByteArrayOutputStream out = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(out);
// do whatever with your zip file
If, instead, you want to open the just retrieved file work with the ZipInputStream:
new ZipInputStream(fileClient.retrieveFileStream(String remote));
Just read the doc here and here
I think you want:
ZipInputStream zis = new ZipInputStream( new ByteArrayInputStream( out.toByteArray() ) );
Then read your data from the ZipInputStream.
As others have pointed out, for what you are trying to do, you don't need to write the downloaded ZIP "file" to the file system at all.
Having said that, I'd like to point out a misconception in your question, that is also reflected in some of the answers.
In Java, a File object does no really represent a file at all. Rather, it represents a file name or *path". While this name or path often corresponds to an actual file, this doesn't need to be the case.
This may sound a bit like hair-splitting, but consider this scenario:
File dir = new File("/tmp/foo");
boolean isDirectory = dir.isDirectory();
if (isDirectory) {
// spend a long time computing some result
...
// create an output file in 'dir' containing the result
}
Now if instances of the File class represented objects in the file system, then you'd expect the code that creates the output file to succeed (modulo permissions). But in fact, the create could fail because, something deleted the "/tmp/foo", or replaced it with a regular file.
It must be said that some of the methods on the File class do seem to assume that the File object does correspond to a real filesystem entity. Examples are the methods for getting a file's size or timestamps, or for listing the names in a directory. However, in each case, the method is specified to throw an exception if the actual file does not exist or has the wrong type for the operation requested.
Well, you could just create a FileOutputStream and then write the data from that:
FileOutputStream fos = new FileOutputStream(filename);
try {
out.writeTo(fos);
} finally {
fos.close();
}
Then just create the File object:
File file = new File(filename);
You need to understand that a File object doesn't represent any real data on disk - it's just a filename, effectively. The file doesn't even have to exist. If you want to actually write data, that's what FileOutputStream is for.
EDIT: I've just spotted that you didn't want to write the data out first - but that's what you've got to do, if you're going to pass the file to something that expects a genuine file with data in.
If you don't want to do that, you'll have to use a different API which doesn't expect a file to exist... as per Qwerky's answer.
Just change the ByteArrayOutputStream to a FileOutputStream.
I'm creating a File mock object with Mockito that will be used as the directory to store a new File.
Folder folder = Mockito.mock(File.class);
File file = new Agent().createNewFile(folder, "fileName");
and inside my Agent class:
public File createNewFile(File folder, String filename){
return new File(folder, "testfile");
}
But I'm getting a NullPointerException at the initialization block of File when creating the new file inside createNewFile method:
java.lang.NullPointerException at java.io.File.<init>(File.java:308)
I think it happens because File doesn't have any empty constructor, so when mocking the object some internal state remains null.
Am I taking the wrong approach mocking the File folder object? My goal is to check some constraints before creating the new file, but I don't want to depend on an existing real folder on the file system.
Thank you.
You need to define the behavior for getPath() for folder as it gets called internally in File class.
You can do it as:
File folder = Mockito.mock(File.class);
when(folder.getPath()).thenReturn("C:\temp\");
File file = new Agent().createNewFile(folder, "fileName");
It will work only till you don't really create a new file but only calling new File.