aspose file tools*
The moose likes Beginning Java and the fly likes Writing a class file to read text file. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Writing a class file to read text file." Watch "Writing a class file to read text file." New topic
Author

Writing a class file to read text file.

Aces Kok Ben
Ranch Hand

Joined: Apr 30, 2011
Posts: 44
Hello Everyone. I just learnt programming a year ago and I was given an assignment to write a class. One of the criteria of the program was:

" write an instance method that reads string from text file and returns as a string to the program.."

This is my code:



I placed the "Data.txt" file in my src folder, but nothing comes out when I run the program. Is there anything wrong? I cannot spot my own mistakes.

By the way, I'm utterly confused and got irritated by the examples i found on the internet. Some suggest using FileReader, some examples even show me BufferedReader. I don't know which should i use in my case.
Ralph Cook
Ranch Hand

Joined: May 29, 2005
Posts: 479
I'm afraid file I/O in java is bound to be a bit daunting for a new programmer. It is definitely a multi-layered affair.

The javadoc for Scanner says "A simple text scanner which can parse primitive types and strings using regular expressions." So you might suspect that you don't need it, because you aren't parsing anything. There's bound to be something simpler, you might say.

FileReader is another possibility, but has no reading methods of its own, and its superclass InputStreamReader has nothing for reading a line. I would regard it as an unnecessary pain in the neck to have to handle reading until end-of-line, etc., surely somewhere in the java standard classes is something to do that.

For your purposes, I think BufferedReader has the method you need, readLine(). It's only drawback is a lack of a constructor that takes a filename.

So you do that with the FileReader, which extends InputStreamReader, which extends Reader, which can be passed to the BufferedReader constructor.

BufferedReader reader = new BufferedReader(new FileReader("Data.txt"));

After that you can execute reader.readLine() to get the next line from Data.txt.

Now. Your current code loops until there is no more input from your Scanner object. So there isn't likely to be a line to print out, in that case. Your current code might work if you just read one line with Scanner and return. But I thought I'd throw in a little about choosing a class to use to read the file while we were at it.

rc
Deep Purohit
Greenhorn

Joined: Mar 29, 2010
Posts: 9

Your program looks ok.
Are you sure there is some content inside the data.txt file?
Try to give absolute path (D:\movies\There_Will_Be_Blood.avi) of the file and reading it.

Now for your frustration part, you can invest just 5 minutes of your time reading:
Scanner, FileReader, BufferedReader

And you'll know that Scanner might just solve the purpose.
Frustration is just the final step of doing something right. So if you are frustrated your are almost there.
Update: Well, rc has explained everything you will need to know. So now you have option of choosing any of it Scanner/BufferedReader.
.
Aces Kok Ben
Ranch Hand

Joined: Apr 30, 2011
Posts: 44
Ralph Cook wrote:I'm afraid file I/O in java is bound to be a bit daunting for a new programmer. It is definitely a multi-layered affair.

The javadoc for Scanner says "A simple text scanner which can parse primitive types and strings using regular expressions." So you might suspect that you don't need it, because you aren't parsing anything. There's bound to be something simpler, you might say.

FileReader is another possibility, but has no reading methods of its own, and its superclass InputStreamReader has nothing for reading a line. I would regard it as an unnecessary pain in the neck to have to handle reading until end-of-line, etc., surely somewhere in the java standard classes is something to do that.

For your purposes, I think BufferedReader has the method you need, readLine(). It's only drawback is a lack of a constructor that takes a filename.

So you do that with the FileReader, which extends InputStreamReader, which extends Reader, which can be passed to the BufferedReader constructor.

BufferedReader reader = new BufferedReader(new FileReader("Data.txt"));

After that you can execute reader.readLine() to get the next line from Data.txt.

Now. Your current code loops until there is no more input from your Scanner object. So there isn't likely to be a line to print out, in that case. Your current code might work if you just read one line with Scanner and return. But I thought I'd throw in a little about choosing a class to use to read the file while we were at it.

rc


Hello RC. Thanks for spending your time to answer my question. It's weird you see, I have another example which my lecturer gave to me last year - it was a GUI thingy codes used to read text files, and upon clicking the button, the Strings in the text file appeared on the textbox. Here's their code:

...

try {
sc = new Scanner (new File (C:\\Practical\\Contacts.txt));
while (sc.hasNextLine()){
inputStr = sc.nextLine();
jTextArea.append(inputStr);
jTextArea.append("\n");
}
sc.close();
...

Why did her codes work and mine does not?

**P.S. By the way how do I indent my codes here in the forum(Like from the first post, with numberings beside)? Sorry this is my first time here in the forum and I don't want to break any rules.
Aces Kok Ben
Ranch Hand

Joined: Apr 30, 2011
Posts: 44
Deep Purohit wrote:Your program looks ok.
Are you sure there is some content inside the data.txt file?
Try to give absolute path (D:\movies\There_Will_Be_Blood.avi) of the file and reading it.

Now for your frustration part, you can invest just 5 minutes of your time reading:
Scanner, FileReader, BufferedReader

And you'll know that Scanner might just solve the purpose.
Frustration is just the final step of doing something right. So if you are frustrated your are almost there.
Update: Well, rc has explained everything you will need to know. So now you have option of choosing any of it Scanner/BufferedReader.
.


Thank you DP. Erm. I tried using the absolute path once but the output was the same:

"File not found"
null
Emmanuel de Ternay
Greenhorn

Joined: Apr 29, 2011
Posts: 5

Scanner is not the right class to read files. You should use instead FileReader associated with BufferedReader, as Ralph Cook said.
Anyway, your method should work. I think the problem is that for each iteration, you replace the content variable with the new line, loosing the previous inserted lines in the variable. And what you see is the last line of your file, maybe a blank line.
Try to change line 22 by:

It should work.
Deep Purohit
Greenhorn

Joined: Mar 29, 2010
Posts: 9

Umm Interesting.. I just executed your program by giving absolute path. It worked!
The single line in text file was "I will play Prince of Persia". And it printed.
So the whole problem lies in the path of the file what you are giving..
Try giving the path like -
**P.S. By the way how do I indent my codes here in the forum(Like from the first post, with numberings beside)? Sorry this is my first time here in the forum and I don't want to break any rules.

I know about eclipse - Click ctrl+shift f
Aces Kok Ben
Ranch Hand

Joined: Apr 30, 2011
Posts: 44
Emmanuel de Ternay wrote:Scanner is not the right class to read files. You should use instead FileReader associated with BufferedReader, as Ralph Cook said.
Anyway, your method should work. I think the problem is that for each iteration, you replace the content variable with the new line, loosing the previous inserted lines in the variable. And what you see is the last line of your file, maybe a blank line.
Try to change line 22 by:

It should work.


I did it. But it didn't work. Here's a screenshot:

http://i54.tinypic.com/atmxi.jpg


Is there really nothing wrong with my program? Is my program logic correct?

FileController fc = new FileController("C:\\Users\\Aces\\workspace\\Year2Sem1\\Practical2\\src.\\Data.txt"); <=== Creation of a FileController object with the constructor that takes in a String

System.out.println(fc.readRequest()); <=== Invokes readRequest method, that returns a String?

Is my explanation correct?

Emmanuel de Ternay
Greenhorn

Joined: Apr 29, 2011
Posts: 5

Put the Data.txt file outside of the src directory (in the project directory if you use eclipse) and you should be able to read the file. I made the test and I could read the file.
If you want to keep it in src directory, you have to put "src/Data.txt" as filename.
Aces Kok Ben
Ranch Hand

Joined: Apr 30, 2011
Posts: 44
Emmanuel de Ternay wrote:Put the Data.txt file outside of the src directory (in the project directory if you use eclipse) and you should be able to read the file. I made the test and I could read the file.
If you want to keep it in src directory, you have to put "src/Data.txt" as filename.


I tried that too. All those didn't work. I've been working from early afternoon till now...
Ralph Cook
Ranch Hand

Joined: May 29, 2005
Posts: 479
Aces Quacck wrote:I tried that too. All those didn't work. I've been working from early afternoon till now...


Saying "it didn't work" is never enough. Obviously things have changed since you last posted the code. Perhaps you should post it again.

rc
Aces Kok Ben
Ranch Hand

Joined: Apr 30, 2011
Posts: 44
Ralph Cook wrote:
Aces Quacck wrote:I tried that too. All those didn't work. I've been working from early afternoon till now...


Saying "it didn't work" is never enough. Obviously things have changed since you last posted the code. Perhaps you should post it again.

rc


Here's the current code I edited:



The output was:
"File not found
RUN HERE"

And here's another approach I took, however I don't know if I'm right:



The output was:
"java.io.FileNotFoundException: C:\Users\Aces\workspace\Year2Sem1\Practical2\src\Data.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at FileController.readRequest(FileController.java:27)
at FileController.main(FileController.java:56)"

I'm sure I placed the file in the right directory but it doesn't work...

http://i52.tinypic.com/1qh6ds.jpg
Ralph Cook
Ranch Hand

Joined: May 29, 2005
Posts: 479
This might be a Windows 7 issue.

Microsoft's Windows 7, in its infinite wisdom, intercepts programs that are opening files in places where it decides they should not, and "redirects" their I/O to another location. I only have experience with it on write operations, but it's the only thing that occurs to me in this situation. Otherwise things look all right to me.

If you want to check out the Windows 7 thing, turn off "User Account Control" (click start, search, enter "UAC", and move the slider bar all the way to the bottom to "Never Notify", the OK out). Then run the program and see if it works.

I don't have anything else to suggest.

rc
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10535
    
    9

Is this the real location C:\Users\Aces\workspace\Year2Sem1\Practical2\src\Data.txt
or this one C:\\Users\Aces\workspace\Year2Sem1\Practical2\src\Data.txt


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Aces Kok Ben
Ranch Hand

Joined: Apr 30, 2011
Posts: 44
Maneesh Godbole wrote:Is this the real location C:\Users\Aces\workspace\Year2Sem1\Practical2\src\Data.txt
or this one C:\\Users\Aces\workspace\Year2Sem1\Practical2\src\Data.txt


C:\Users\Aces\workspace\Year2Sem1\Practical2\src\Data.txt
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40029
    
  28
Ryan Falzon,
Your post was moved to a new topic.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Writing a class file to read text file.