• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to read a .txt file and open its contents

 
Zahra Vir
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I really need help. I am trying to display the contents of a text file by having an openFile() method.

Here is my code so far:

private void openFile()
{
JFileChooser chooser = new JFileChooser();

int result = chooser.showOpenDialog(this);

if(result == JFileChooser.CANCEL_OPTION)
return;

//obtain selected file
File fileName = chooser.getSelectedFile();

try
{
//Buffered Reader
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String empData = reader.readLine();
}
catch(IOException ioException)
{
JOptionPane.showMessageDialog(this, "FILE ERROR", "FILE ERROR", JOptionPane.ERROR_MESSAGE);
}
}
This is just a small portion of the code from a much larger problem. If anyone can help me sort this out I am willing to send the whole file.

Thanks
[ December 04, 2004: Message edited by: Zahra Vir ]
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34839
369
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Zahra,
Welcome to JavaRanch!

What problem are you having with the code? The only thing I see offhand is that reading from the file should be done in a loop. Otherwise, you only get the first line.
 
Srinivasa Raghavan
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Zahra,
Use a reader object like BufferedReader

 
Zahra Vir
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks guys.

i still have the same problem, however, i have modified my code somewhat to get the following...

while (input != null)
{
StringTokenizer tokenizer = new StringTokenizer(input);

//Sets the ID token
int id = Integer.parseInt(tokenizer.nextToken());
//Sets the Name token
String name = tokenizer.nextToken();
//Sets the Phone Number Token
String phoneNo = tokenizer.nextToken();
//Sets the Years token
int years = Integer.parseInt(tokenizer.nextToken());
//Sets the Title token
String title = tokenizer.nextToken();

//Now, depending on what the title is, we can find out what additional info is needed
if (title.equals("Professor"))
{
int paper;

if (paperField.getText().equals("")) paper = 0;
else paper = Integer.parseInt(paperField.getText());
}

else if (title.equals("Manager"))
{

}

else if (title.equals("Engineer"))
{

}

//The next record can now be read, and the same process will continue
//input = reader.readLine();
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic