aspose file tools*
The moose likes Beginning Java and the fly likes Reference Specific Line in Text File Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Reference Specific Line in Text File" Watch "Reference Specific Line in Text File" New topic
Author

Reference Specific Line in Text File

Roger Sanchez
Greenhorn

Joined: Jun 23, 2003
Posts: 16
I am trying to create an applet that reads lines of text from a text file when a JButton is clicked. Each line of text will be set to a different text field in the GUI. I was able to get the applet to read the text file but it sets the entire contents of the file to the individual text fields. Can anyone help? Thanks.
Here is the code I have to date:
// Display the file in the student text fields
private void showFile()
{
// Use a BufferedReader to read text from the file
BufferedReader infile = null;
// Get file name from the text field
String filename = "students.txt";
String inLine;
try
{
// Create a buffered stream
infile = new BufferedReader(new FileReader(filename));
// Read a line and append the line to the text fields
while ((inLine = infile.readLine()) != null)
{
jtfStudentID.setText(inLine + '\n');
jtfLastName.setText(inLine + '\n');
jtfFirstName.setText(inLine + '\n');
jtfAddress.setText(inLine + '\n');
jtfCity.setText(inLine + '\n');
jtfProvince.setText(inLine + '\n');
jtfPcode.setText(inLine + '\n');
jtfPhone.setText(inLine + '\n');
jtfEmail.setText(inLine + '\n');
}
}
catch (FileNotFoundException ex)
{
System.out.println("File not found: " + filename);
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
finally
{
try
{
if (infile != null) infile.close();
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
}
Leslie Chaim
Ranch Hand

Joined: May 22, 2002
Posts: 336
I don't think this is an I/O problem
You're just re-setting the same fields over-and-over in your loop.
I infer that you files follows a structure where each line corresponds to a field on your form/applet/whatever.
There are many ways to crack this, I think that an array of JTextField and do something like this.

Whatever the case you need to build some sort of mapping to do this.
Cheers,
Leslie


Normal is in the eye of the beholder
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671



"I'm not back." - Bill Harding, Twister
Roger Sanchez
Greenhorn

Joined: Jun 23, 2003
Posts: 16
I'm still confused .... do I replace my existing code with the one you provided or add to my code?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Replace your code - what you're doing is reading a line once, then assigning that line's value to all the fields, then reading another line, assigning that same value to all the fields (overwriting the old value), etc. It shouldn't come as a surprise that all the fields have the same value - just lok at the code.
Here's another version:

Here I assumed infile was a member variable, since I didn't feel like passing it around as a parameter, but that's up to you.
Roger Sanchez
Greenhorn

Joined: Jun 23, 2003
Posts: 16
I implemented your code as follows:
void showFile()
{
// Use a BufferedReader to read text from the file
BufferedReader infile = null;
// Get file name from the text field
String filename = "students.txt";

// Create a buffered stream
infile = new BufferedReader(new FileReader(filename));
String line;
setup(jtfStudentID);
setup(jtfLastName);
setup(jtfFirstName);
setup(jtfAddress);
setup(jtfCity);
setup(jtfProvince);
setup(jtfPcode);
setup(jtfPhone);
setup(jtfEmail);
}

private void setup (JTextField jtf) {
String line = infile.readLine();
if (line == null)
throw new RuntimeException("This infile sucks");
jtf.setText(line + '\n');
}
However, I receive an error when trying to compile stating that the VARIABLE INFILE cannot be resolved. This is strange because this variable was recoginzed in other methods but not this one. Please help!!!
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
From my previous post:
Here I assumed infile was a member variable
This means that infile would have to be declared at the member variable level, not in a method:

However this may not be very good OO design for your class if the infile is not needed as part of the permanent state of your class - i.e. you don't really need the file after the text fields have been set up, right? It's probably better to do a little more typing and use a local variable for infile as you did originally. The main benefit I saw in creating a setup() method was to do some extra error checking for you. Here's another version:
Roger Sanchez
Greenhorn

Joined: Jun 23, 2003
Posts: 16
You've been really helpful, Jim. However, I'm still having difficulty implementing the code that you provided. Basically, I have three text files that I need to import information from and populate textfields with (students.txt, courses,txt and marks.txt). I also need to scroll through records the various records using forward and back JButtons. It feels as though I've tried everything and still can't get this to work!(I'm fairly new to JAVA but am getting a little frustrated). I spent alot of time creating the GUI interface with all the text fields, JButtons, labels, etc. Do you think you can help? Please see my full applet source code below to see what I've completed to date (this code does compile if you want to see the interface):

[ June 25, 2003: Message edited by: Jim Yingst ]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Hmmm... most of this has little to do with I/O, so I'll move this to Java in General - beginner. See you there...
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
So, now that we're here...
Urk. That's a bit more code than I want to deal with right now. A few thoughts though:
Always use [code] tags when you post code here - they maintain the indentation of your code, which improves readability.
Try working on a smaller version of your applet, with just a few fields, and figure out how to set that up before putting in all those other lines.
Consider splitting the project into several smaller classes. E.g. you might have one class for the student info (displayed on a JPanel), and another for the course info (also on a JPanel), and then all the applet does is hold two JPanels. Maybe there are more subdivisions necessary - I'm not sure how all the data relate. But it's a good idea to keep individual classes small and manageable, especially when you're learning. Makes it easier to see how the parts fit together.
Don't worry too much about exact positioning of all those fields and labels yet. In the long run you'll probably want to use some sort of layout manager anyway.
As for reading the input file and displaying text fields - well, I see the various showFile(), showCourses(), showMarks() methods, still using the same code that you had originally. Have you tried changing the code to look like one of the other examples we showed you? What does it look like? Do you get an error message? It's difficult to address something like this in general without more specific feedback. Just pick one method, like showFile(), and focus on that until it's working more like you want. Or post again with more specific feedback about you rproblem. Good luck...
Francis Siu
Ranch Hand

Joined: Jan 04, 2003
Posts: 867
hi Roger
Each line of text will be set to a different text field in the GUI. I was able to get the applet to read the text file but it sets the entire contents of the file to the individual text fields.
please consider your part of the coding
I will put the (*) to show you which will create the effect of suck

Actually,you can use other method such as for loop and using (if--else if or switch)condition to check the content(line) that it is belong to which line matching with your textField when you read.
The suggestion solution may be putting the record number at the beginning of the record or read the StudentID as the beginning,so that you can count the number of line(details) should be read by the programme each time.
The following is the text file
1
StudentID
....
2
StudentID
...
In your programme,you can use for loop to read nine times for each record.(This can be reduce some of the coding)
So,you can keep check of each record
If you do not understand what I mean
please post again

[ June 26, 2003: Message edited by: siu chung man ]

Francis Siu
SCJP, MCDBA
Roger Sanchez
Greenhorn

Joined: Jun 23, 2003
Posts: 16
I have simplified my code to one textfield and three JButtons. It nows reads as follows:

I am trying to populate the textfield with the first StudentID record from the students.txt text file when the STUDENTS JButton is clicked. When the -> JButton is clicked, the second record (or line) should be displayed in the textfield. When I attempt to compile the code above, I receive two errors: one on line 106 and one of line 108. Please provide a recommendation on how to proceed.
Thanks
Francis Siu
Ranch Hand

Joined: Jan 04, 2003
Posts: 867
Ar....
Roger
the second record (or line) should be displayed in the textfield. When I attempt to compile the code above, I receive two errors: one on line 106 and one of line 108.
Could you give us the line number in your posted programme and the error message?
thanks
Roger Sanchez
Greenhorn

Joined: Jun 23, 2003
Posts: 16
To clarify your response, the first record in "students.txt" should be displayed in jtfStudentID. When the "->" JButton is clicked , the second record in "students.txt" should be displayed in the jtfStudentID. When the "->" JButton clicked again, the third record should be displayed in jtfStudentID; and so on. After the final record is displayed in jtfStudentID, the first record should be displayed in jtfStudentID. I also need the reverse functionality in the "<-" JButton - to be able to scroll through the "students.txt" lines in reverse order. Below is the content of the "students.txt" file:
0000000
1111111
2222222
3333333
4444444
5555555
6666666
7777777
8888888
9999999

The error messages received when trying to compile the applet are:
TME4.java:106: cannot resolve symbol
symbol: variable line
location: class TME4
if (line == null)
TME4.java:106: cannot resolve symbol
symbol: variable line
location: class TME4
jtf.setText(line + '\n')
I hope you can help.
Thanks
Francis Siu
Ranch Hand

Joined: Jan 04, 2003
Posts: 867
yes Roger
Actually,I want to help you complete the previous programme because you do not know what I want to say,just need to add some condition in it, then it run if without any error in the original programme,so do not need to change it to current one because you may not know some concept

you without DECLARE the variable line in your programme,so what is the purpose of the variable line,so change it to
(inLine = infile.readLine()) == null
please wait, I will help you finish the previous one.
Roger Sanchez
Greenhorn

Joined: Jun 23, 2003
Posts: 16
I'll wait for your reply. Thanks for much for your help.
Francis Siu
Ranch Hand

Joined: Jan 04, 2003
Posts: 867
Ar... finish
I think that you work very hard
about 450 line

But you should notice that when you click the button once,the details read from a file and whether the pointer will stand in the current location or return to the beginning,this point I am not sure and without test.
If it does not work and compiler error,please post it again
Roger Sanchez
Greenhorn

Joined: Jun 23, 2003
Posts: 16
Thanks so much, Siu! The program compiled without errors and displayed the required data (some of the "marks" field need to calculate the number of courses the student has completed and average grades, though).
Also, I would still appreciate some help with the "->" and "<-" JButtons to scroll throught the student records and display them in the appropriate JTextFields. Can you also help with this?
You've been incredibly helpful!

Here are the complete .txt files below.
"students.txt":
0000000
Bach
Sebastian
2222 22 Avenue
Edmonton
AB
T2T 2T2
780-222-2222
bachs@telusplanet.net
1111111
Tchaikovsky
Pyotr Ilyich
3333 33 Street
Vancouver
BC
V3V 3V3
604-333-3333
chaiko@connect.bc.ca
2222222
Strauss
Johann
4444 Vienna Crescent, North West
Saskatoon
SASK
S4S 4S4
306-444-4444
jstrauss@frisky.net
3333333
Handel
George Frideric
Appartment 1685 1759 Hamburg Plaza
Winnipeg
MA
W5W 5W5
314-555-5555
concerto@allegro.com
4444444
Vivaldi
Antonio
1678 66 Avenue
Venez
ON
Z6Z 6Z6
416-666-6666
vivaldi@grosso.padrona.net
5555555
Mozart
Wolfgang A.
1756 Bavarian Boulevard
Salzburg
ON
S0S 0S0
416-555-5555
magic@cs.flute.ca
6666666
Haydn
Franz
#66 Eszterhaza Place
Mississauga
ON
M6M 6M6
416-666-6666
neusiedler@primrose.net
7777777
Beethoven
Ludwig, Van
777 Longandwinding Road
Fort McMurray
AB
T7T 7T7
780-777-7777
ludwig@tihuana.brass.net
8888888
Mahler
Gustav
1860 Piazza del Torro 11
Madrid
Spain
MS 6611
66-123-888-888
gustavm@europa.esp
9999999
Dvorak
Antonin
9999 Romantic Avenue
Montreal
QU
Q9Q 9Q9
816-999-999
anton@orchestra.net
"courses.txt":
COMP 111
Relativity in Computing
Alfred Einstein
COMP 222
Computers and Uncertainties
Bradley Heisenberg
COMP 333
Robotics
Chester Von Neumann
COMP 444
Sanity in a Digital World
Douglas Freud
COMP 555
Management Systems
Elmer Socrates
COMP 666
Systems Management
Florence Damocles
"marks.txt":
0000000
COMP 111
71
1111111
COMP 111
100
1111111
COMP 222
100
2222222
COMP 111
69
2222222
COMP 222
74
2222222
COMP 555
84
3333333
COMP 111
67
3333333
COMP 222
72
3333333
COMP 444
77
3333333
COMP 666
87
5555555
COMP 111
65
5555555
COMP 222
70
5555555
COMP 444
75
5555555
COMP 555
80
5555555
COMP 666
85
6666666
COMP 111
63
6666666
COMP 222
68
6666666
COMP 444
73
7777777
COMP 111
61
7777777
COMP 222
66
7777777
COMP 444
71
7777777
COMP 555
76
8888888
COMP 111
59
8888888
COMP 222
64
8888888
COMP 444
69
9999999
COMP 111
57
9999999
COMP 222
62
9999999
COMP 444
67
9999999
COMP 555
72
9999999
COMP 666
83
Francis Siu
Ranch Hand

Joined: Jan 04, 2003
Posts: 867
Ar.. Roger
Actually,many ranchers are better than me for the knowledge of JAVA
I can only help you to find out what wrong in the programme,sorry that I can not help you for the following task.
I wonder if you can do it yourself for the following task
I will stay around in this Java in General (beginner) forum.
So,if you can not solve some trouble problems,you can post it as a new topic.
As we know,no one can walk if whose without try
:roll:
Roger Sanchez
Greenhorn

Joined: Jun 23, 2003
Posts: 16
Understood. Thanks again for all your help! I will take another stab at it.
Take care,
RS
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reference Specific Line in Text File