• Post Reply Bookmark Topic Watch Topic
  • New Topic

Reading a File into Java  RSS feed

 
David Sheridan
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to read a text file into Java and split the text into tokens. Eventually I want to be able to count the number of instances of a specific word. However, at this point, when I run the file, all I get is the location of the file rather than the text in the file. I am new to Java, so any help would be great.

 
Heena Agarwal
Ranch Hand
Posts: 262
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is happening cause you are neither reading, nor splitting the file content into tokens.

You are just splitting whatever the str variable has.

Put a
in yout code, so you'll know what String your program is trying to split.

You might also want to refer to the API docs for information on how to read a text file in Java.
 
Heena Agarwal
Ranch Hand
Posts: 262
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh and welcome to Coderanch.
 
Scott Winterbourne
Ranch Hand
Posts: 116
2
Eclipse IDE Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, please use Code tags when posting code. This will make your code much easier to read when trying to help you solve your problem.

Regards,
 
Scott Winterbourne
Ranch Hand
Posts: 116
2
Eclipse IDE Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In your Words() method here:



You are trying to create tokens from the file name rather than the content of the file.

You have created a new Scanner object called "reader". It seems to me you would need to invoke some method on the reader object to read the lines from the text file before you can create tokens from it.

Take a look at the Java documentation for the Scanner class here http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html. Scroll down to the Method Summary section for a list of methods you can use to read the contents of the text file.

  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!