1

I want to read from a client's inputstream in two different ways:

1: Use Scanner over the inputstream to read strings.

2: Use the InputStream object itself to read a file with a buffer.

At first, I want to read a text, that gives me the name and size of the File, in my case: "file:name:...", "file:size:...".

When I have this information, the InputStream should actually read the file. The problem is, that I try to read the file in the "scanner.hasNextLine()"-loop with the InputStream object but this causes the InputStream.read() method to return -1 or EOS. I have brought the problem to a minimal size so you just have to answer me this question:

Why does the read-method return -1 here:

if (scanner.hasNextLine()) {        
    System.out.println(inputstream.read());
}
Blake Yarbrough
  • 2,286
  • 1
  • 20
  • 36
R. Völker
  • 40
  • 1
  • 5
  • 3
    Please include more code. The easy answer to "Why ... -1" is that end of file was reached, and that's no help. – DSlomer64 Aug 07 '15 at 19:57
  • 2
    Why do you read through ``Scanner`` **and** ``InputStream``? – Jean Logeart Aug 07 '15 at 19:59
  • I use `Scanner` and `InputStream` because with the `Scanner`, I want to read the incoming commands and with the `InputStream` I want to read the file which can be **different** from a text file. – R. Völker Aug 09 '15 at 13:50

2 Answers2

2

As the Oracle Documentation for Scanner.hasNextLine() states, this method does not advance the Scanner. This means that you could be perpetually looking at the first line of your file with your Scanner, while advancing your InputStream. This means that even though the Scanner has a next line, the InputStream may not. You appear to be walking off the end of the file with the InputStream.

If you do not advance the Scanner along with the input stream, you cannot know that the Scanner is looking at the same location in the file. It is dubious at best to read one file simultaneously with a Scanner and an InputStream anyway.

Consider refactoring your code to only use one or the other.

If you would like to read the entire contents of the file into a single String, consider this:

static String readFile(String path, Charset encoding) 
  throws IOException 
{
  byte[] encoded = Files.readAllBytes(Paths.get(path));
  return new String(encoded, encoding);
}

and other methods from How do I create a Java string from the contents of a file?

Community
  • 1
  • 1
Blake Yarbrough
  • 2,286
  • 1
  • 20
  • 36
-1

Okay I don't need Scanner and InputStream anymore. I can do both, sending texts and files, with the DataOutputStream (with writeUTF(String) and write(byte[], int, int)). This really works very well and simplifies my code a lot.

Don't say this is dobious! If you have a Socket, sometimes you need to use the InputStream in two or three different ways. And I didn't want to use two Sockets.

R. Völker
  • 40
  • 1
  • 5