想请问为什么fileInputStream.read() != -1这样判断不行,必须用available()>0呢
想请问为什么fileInputStream.read() != -1这样判断不行,必须用available()>0呢
正在讨论
评论 (6)
- 受欢迎
- 新
- 旧
你必须先登录才能发表评论
Qin-1999
26 一月, 08:14
同问
0
Guadalupe Gagnon
10 六月 2021, 13:19
What are you doing with the value returned from the read() method? That line, while it does return true as long as .read() does not return -1, there isn't a way for that line to use the value of the .read() method. You are probably looking for something more like this:
0
Qin-1999
26 一月, 08:17
Yes, we are discussing why using " " is incorrect. As far as I know, in Java, when you read data from an input stream (like FileInputStream), if it has already reached the end of the data source (meaning there is no more data to read), the read() method will return -1. This is standard behavior in Java I/O, not something introduced in a specific version.
+1
Guadalupe Gagnon
26 一月, 17:46
The original poster made an error in their code by not saving the value being read with fileInputStream.read() != -1. Their code was something like this:
which means they were reading from the stream 2 times each loop cycle but only saving the data from the read() method one time. This would result in half the data being lost. When they changed it to:
The code passed because now because only 1 line reads the data and saves it and no data is lost.
Their conclusion that you must use .available() > 0 was incorrect as they just had a logical error in their original code.
You might be commenting on the wrong post because no one has mentioned using " ". 0
Qin-1999
27 一月, 00:41
Haha, I didn’t reply to the wrong post. I just forgot to paste the code inside that quote.
I have the same opinion as you. Thank you for your reply.
+1
Guadalupe Gagnon
27 一月, 05:09
Ahhh. I see 🙃🙂🙃
0