Reading a file in java using fileinputstream - java

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.

Related

NoSuchFileException in Files.newInputStream with StandardOpenOption.CREATE

I am trying to open a file for reading or create the file if it was not there.
I use this code:
String location = "/test1/test2/test3/";
new File(location).mkdirs();
location += "fileName.properties";
Path confDir = Paths.get(location);
InputStream in = Files.newInputStream(confDir, StandardOpenOption.CREATE);
in.close();
And I get java.nio.file.NoSuchFileException
Considering that I am using StandardOpenOption.CREATE option, the file should be created if it is not there.
Any idea why I am getting this exception?
It seems that you want one of two quite separate things to happen:
If the file exists, read it; or
If the file does not exist, create it.
The two things are mutually exclusive but you seem to have confusingly merged them. If the file did not exist and you've just created it, there's no point in reading it. So keep the two things separate:
Path confDir = Paths.get("/test1/test2/test3");
Files.createDirectories(confDir);
Path confFile = confDir.resolve("filename.properties");
if (Files.exists(confFile))
try (InputStream in = Files.newInputStream(confFile)) {
// Use the InputStream...
}
else
Files.createFile(confFile);
Notice also that it's better to use "try-with-resources" instead of manually closing the InputStream.
Accordingly to the JavaDocs you should have used newOutputStream() method instead, and then you will create the file:
OutputStream out = Files.newOutputStream(confDir, StandardOpenOption.CREATE);
out.close();
JavaDocs:
// Opens a file, returning an input stream to read from the file.
static InputStream newInputStream(Path path, OpenOption... options)
// Opens or creates a file, returning an output stream that
// may be used to write bytes to the file.
static OutputStream newOutputStream(Path path, OpenOption... options)
The explanation is that OpenOption constants usage relies on wether you are going to use it within a write(output) stream or a read(input) stream. This explains why OpenOption.CREATE only works deliberatery with the OutputStream but not with InputStream.
NOTE: I agree with #EJP, you should take a look to Oracle's tutorials to create files properly.
I think you intended to create an OutputStream (for writing to) instead of an InputStream (which is for reading)
Another handy way of creating an empty file is using apache-commons FileUtils like this
FileUtils.touch(new File("/test1/test2/test3/fileName.properties"));

using FileInputStream and FileOutputStream

Hi I had a couple of questions about using the FileInputStream and FileOutputStream classes.
How would FileInputStream objects locate a file it is trying to read in?
Where would FileOutputStream save a file to?
Thanks.
Strange question and I will give a strange answer.
First part: don't use either, use Files:
final Path src = Paths.get("some/file/somewhere");
final InputStream in = Files.newInputStream(src);
// ...
final Path dst = Paths.get("another/file");
final OutputStream out = Files.newOutputStream(dst);
Note that Path objects are in essence abstract: nothing guarantees that they point to a valid entry. If they don't, the Files methods above will throw a NoSuchFileException (file does not exist), or an AccessDeniedException (sorry mate, you can't do that), or any relevant exception.
Second part: File*Stream
The basics are the same: if you are stuck with Java 6 you have to use File instead of Path, but File is as abstract as Path is; it may, or may not, point to a valid location.
When you issue:
final String dst = "/some/file";
new FileOutputStream(dst);
internally, FileOutputStream will create a File object; which means the above is equivalent to:
final String dst = "/some/file";
final File f = new File(dst);
new FileOutputStream(f);
Conclusion: no, File*Stream does not know per se whether a file exists as long as it does not try to open it. Paths as well as Files are completely abstract until you try and do something with them.
And do yourself a favour: use the new file API which Java 7+ provides. Have you ever tried to initiate a FileInputStream with a File which exists but you cannot read from? FileNotFoundException. Meh. Files.newInputStream() will at least throw a meaningful exception...
Generally, you simply pass the file object to the stream instantiations.
FileInputStream is = new FileInputStream(f);
FileOutputStream os = new FileOutputStream(f);
BufferedInputStream is2 = new BufferedInputStream(is);
BufferedOutputStream os2 = new BufferedOutputStream(os);
Also consider using Printwriter for the output stream when you are working with text files.
About Streams:
Streams are objects that allow an app to communicate with other programs.
To directly answer your question, in Java, here is how I would use the Streams.
//You need to import a few classes before you begin
import java.io.FileInputStream;
import java.io.FileOutputStream;
You can declare them this way
FileInputStream is = new FileInputStream("filename.txt"); //this file should be located within the project folder
For output stream, it can be accessed a similar way:
FileOutputStream os = new FileOutputStream("filename.txt"); //this file should be located within the project folder
More Information:
I recommend using a PrintWriter when trying to write to text files. To do this, you would implement the following:
import java.io.PrintWriter;
Then use this to write to the file:
PrintWriter pw = new PrintWriter(OUTPUT_STREAM);
I also recommend using the Scanner class when reading in user data:
import java.util.Scanner;
Then use this to read the input:
Scanner kb = new Scanner(INPUT_STREAM); //now you can access this data by using methods such as nextInt, nextDouble, etc...

FileDescriptor of Directory in Java

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();
}

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.

How to create a java.io.File from a ByteArrayOutputStream?

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.

Categories

Resources