I encountered a problem in the process of learning stream programming. First, let's take a look at the java source program I wrote:
Package StreamLearn; import java. io. *; public class TestFileInputStream {public static void main (String [] args) {int count = 0; FileInputStream in = null; try {in = new FileInputStream ("c: \. java ");} catch (FileNotFoundException e) {System. out. println ("can not find it"); System. exit (1) ;}long num = 0; try {while (count = in. read ())! =-1) {System. out. print (char) count); // System. out. println (count); num ++ ;}} catch (IOException e) {e. printStackTrace ();} System. out. println ("\ n characters:" + num );}}
This code function is very simple. It reads characters from the. java file and counts the number of characters. Let's take a look at the specific content in the. java file: The running result of the program is as follows: 123, 456, characters, and 10 characters. Why does it change to 8 characters when there are only 6 characters? Let's improve the source code:
Package StreamLearn; import java. io. *; public class TestFileInputStream {public static void main (String [] args) {int count = 0; FileInputStream in = null; try {in = new FileInputStream ("c: \. java ");} catch (FileNotFoundException e) {System. out. println ("can not find it"); System. exit (1) ;}long num = 0; try {while (count = in. read ())! =-1) {// System. out. print (char) count); System. out. println (count); num ++ ;}} catch (IOException e) {e. printStackTrace ();} System. out. println ("\ n characters:" + num );}}
The running result is as follows: 4950511310525354 characters: 8