If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Enjoy an ad free experience by logging in. Not a member yet? Register.

How to read in text files?

Hi,

I need to be able to create a very simple Java program (not javascript) which reads in a text file and then outputs it's contents to the screen. Although it sounds very simple I am an extreme beginner and was looking for some help.

Here's an example of how to read in the contents of a text file. By the way, you were going to try to call the readData method from main, which can't happen without readData being static, too. I just called it from the constructor as you'll see:

Are you learning Java from online tutorials? If so, I sincerely recommend getting a book, esp. to begin with and get a solid background of the language. I've been promoting Bruce Eckel's Thinking in Java books since I originally picked Java up from the 2nd edition (when J2SDK1.3 was out), and I think they're the best free resources available for learning Java. They're available for free in downloadable form, but you can also buy them on paper or CD-ROM.

http://www.mindview.net/Books/TIJ/ -- the 2nd edition was about a two week read (while doing other things of course), and I expect the third edition to take about as long to read.

Also of interest if you're using Java 1.4+ will be the java.nio packages; they're more complex to use because they're lower-level, but that also makes the new I/O system more efficient. This example, which I borrowed from Thinking in Java, 3rd Edition by Bruce Eckel (see above) will copy one file to another using the new I/O system (bytebuffers and channels):