JavaDeploy
SiteMap
Java Certification
Java Beans
Java-OO Concepts
Java Input/Output
« Prev
Java Basics
System Object Model
Interfaces Packages
Describe Java Package
Importing Packages
Access Control
Interface Role
Reclaiming Memory
Garbage Collection
Forcing GarbageCollection
Project Access Control
OOA Concepts
Java Exceptions
Exceptions - Quiz
Catching Exceptions-Quiz
Finally-Keyword -Quiz
Throwing Exceptions - Quiz.
Catching Exceptions Baseball
Common Java Exceptions
Java Multitasking
Using Join for Threads
Starting JavaThread - Quiz
Coordinating Java Threads - Quiz
Thread States -Quiz
Intro Java Input/Output
Java Io Package
Java System.in Read Input
Data Input Stream
File Class To Access Files
Save Restore Draw Applet Project
Java Class Input Output Review
Java Stream Programming Conclusion
Reading File Java - Exercise
Read from a File
Objective:
For this exercise, write a character-mode, stand-alone program that reads from a file and counts and displays the number of characters in this file. The file to read should be passed to the program as a command-line argument. (In other words, the file to read will be a string in
args[0]
in your program's
main()
method.)
To create a stream that you can use to read from a file, you can create an instance of
FileInputStream
. To create this instance, pass its constructor a string instance representing the file to read. To read a byte, you can use an instance method defined by
FileInputStream
called
read()
. When
read()
returns the value -1, it has reached the end of the file. So, you can keep on looping, reading, and counting until you get -1.
Try running the file on itself. In addition, use the
try
/
catch
block where appropriate to handle any
IOException
errors.) Place your code in the text area below when you are satisfied that it is working correclty.