简体   繁体   中英

Reading with InputStream while using Scanner

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM