It's not a secret anymore!
The moose likes Beginning Java and the fly likes Reading from file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Reading from file" Watch "Reading from file" New topic

Reading from file

Marc Kryzhan

Joined: Mar 17, 2004
Posts: 14
I've successfully read from a file; proven because I wrote to a text file by copying from a file. How do I do a System.out.println of the contents of a file? Here's my code that I used to write a file and inwhich I've also attempted to output the encoded contents of my file with println. The file I read from is called farrago.txt (from sun's site). I modified it to contain two lines of text.
public class Copy {
public static void main(String[] args) throws IOException {
File inputFile = new File("farrago.txt");
File outputFile = new File("outagain.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = != -1)
System.out.println("ToString " + out.toString());
System.out.println("Read " +;
System.out.println("Encoding " + in.getEncoding());
System.out.println("Can Read? " + inputFile.canRead());
System.out.println("Path " + inputFile.getPath());
System.out.println("Length " + inputFile.length());

//System.out.println("..." + getEncoding();

Newbee to java.
Tim West
Ranch Hand

Joined: Mar 15, 2004
Posts: 539
Hi Marc, returns an int - the character code of the char you read. You need to cast this to a char when printing out.
With minimal changes to your code, this works:

However, you'll find that I/O in Java can be made much easier (or more complicated, depending on your point of view) by combining the various classes available for reading and writing.
Thus some equivalent code is:

The advantage of the code above is that you get a whole line at a time - this is often very useful. Other classes are available for reading from zip files, from sockets, from just about anything...and writing back. :-)
[ March 29, 2004: Message edited by: Tim West ]
Nathaniel Stoddard
Ranch Hand

Joined: May 29, 2003
Posts: 1258
You can read the contents of the file into a buffer of bytes (ie byte[]) and then just System.out.print(buffer), over and over until you reach the end of the file. Is that what you are thinking?

Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Moving this to the I/O and Streams forum...
[ March 29, 2004: Message edited by: Dirk Schreckmann ]

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: Reading from file
jQuery in Action, 3rd edition