Stream Input/Output example

Source: Internet
Author: User

/*

The WC () method operates on any input stream and calculates the number of characters, number of lines, and number of words. It tracks the parity and space of words in lastnotwhite. If no parameter is specified, wordcount uses system. In as the source code to generate an inputstreamreader object. The stream is then passed to the actual counting WC () method. When one or more parameters are executed, wordcount assumes that these file names exist and creates a filereader for each file. The filereader object storing the results is passed to the WC () method. In both cases, the results are printed before exiting.

*/

// A word counting utility.
Import java. Io .*;
Class wordcount {
Public static int intwords = 0;
Public static int intlines = 0;
Public static int intchars = 0;
Public static void WC (inputstreamreader ISR) throws ioexception {
Int C = 0;
Boolean lastwhite = true;
String whitespace = "/T/N/R ";
While (C = ISR. Read ())! =-1 ){
// Count characters.
Intchars ++;
// Count lines.
If (C = '/N '){
Intlines ++;
}
// Count words by detecting the start of a word
Int intindex = whitespace. indexof (C );
If (intindex =-1 ){
If (lastwhite = true ){
++ Intwords;
}
Lastwhite = false;
} Else {
Lastwhite = true;
}
}
If (intchars! = 0 ){
++ Intlines;
}
}
Public static void main (string [] ARGs)
{
Filereader fr;
Try {
If (ARGs. Length = 0 ){
// We're working with stdin
WC (New inputstreamreader (system. In ));
} Else {
// We're working with a list of files.
For (INT I = 0; I <args. length; I ++ ){
Fr = new filereader (ARGs [I]);
WC (FR );
}
}
} Catch (ioexception e ){
Return;
}
System. Out. println (intlines + "" + intwords + "" + intchars );
}
}

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.