Line breaks for reading text files from Java input streams

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.