I want to know if an InputStreamn is empty, but without using the methods read(). Is there a way to know if it's empty without reading from it?
I think you are looking for inputstream.available()
. It does not tell you whether its empty but it can give you an indication as to whether data is there to be read or not.
No, you can't. InputStream
is designed to work with remote resources, so you can't know if it's there until you actually read from it.
You may be able to use a java.io.PushbackInputStream
, however, which allows you to read from the stream to see if there's something there, and then "push it back" up the stream (that's not how it really works, but that's the way it behaves to client code).
Depending on which subclass it really is: http://java.sun.com/j2se/1.4.2/docs/api/java/io/InputStream.html#available() might be sufficient.
You can use the available()
method to ask the stream whether there is any data available at the moment you call it. However, that function isn't guaranteed to work on all types of input streams. That means that you can't use available()
to determine whether a call to read()
will actually block or not.
If the InputStream
you're using supports mark/reset support, you could also attempt to read the first byte of the stream and then reset it to its original position:
input.mark(1);
final int bytesRead = input.read(new byte[1]);
input.reset();
if (bytesRead != -1) {
//stream not empty
} else {
//stream empty
}
If you don't control what kind of InputStream
your're using, you can use the markSupported()
method to check whether mark/reset will work on the stream, and fall back to the available()
method or the java.io.PushbackInputStream
method otherwise.
How about using inputStreamReader.ready() to find out?
import java.io.InputStreamReader;
/// ...
InputStreamReader reader = new InputStreamReader(inputStream);
if (reader.ready()) {
// do something
}
// ...
import java.io.*; public class FileTest { public static void main (String [] args) throws IOException { BufferedReader wow=new BufferedReader (new InputStreamReader (System.in));
System.out.print ("Enter File Name: ");
String fileInput=wow.readLine();
FileInputStream in=new FileInputStream(fileInput);
//FileInputStream out=new FileInputStream(fileOutput);
}
}