difficulty trying to view the contents of a text file in JTextArea
hello.
Im having difficulty trying to view the contents of a text file in a JTextArea. when i run the following program, i press the View Order button. but no data from the Order.txt file is being displayed in the text area. where am i going wrong?
import java.awt.BorderLayout;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
publicclass ViewOrderextends JFrame{
JPanel pnlText, pnlBody, pnlFooter;
JButton btnViewOrder;
JButton btnReturnToOrderSystem;
JLabel jl;
JTextArea jta;
Container contentpane;
public ViewOrder(){
super("View Order");
contentpane = getContentPane();
contentpane.setLayout(new BorderLayout());
pnlText =new JPanel();
pnlBody =new JPanel();
pnlFooter =new JPanel();
jta =new JTextArea(250, 250);
jta.setFont(new Font("Serif", Font.PLAIN, 12));
// Set lineWrap and wrapStyleWord true for the text area
//jta.setLineWrap(true);
//jta.setWrapStyleWord(true);
//jta.setEditable(false);
// Create a scroll pane to hold the text area
JScrollPane jsp =new JScrollPane(jta);
// Set BorderLayout for the panel, add label and scrollpane
pnlBody.add(jsp, BorderLayout.CENTER);
jl =new JLabel("Text retrieved from file:");
btnViewOrder =new JButton("View Order");
btnReturnToOrderSystem =new JButton("Return to Order System Menu");
pnlText.add(jl);
pnlFooter.add(btnViewOrder);
pnlFooter.add(btnReturnToOrderSystem);
contentpane.add(pnlText,BorderLayout.NORTH);
contentpane.add(pnlBody,BorderLayout.CENTER);
contentpane.add(pnlFooter,BorderLayout.SOUTH);
setSize(500, 500);
setVisible(true);
btnViewOrder.addActionListener(new ActionListener(){
publicvoid actionPerformed(ActionEvent e){
//Read from file
try{
String inputFileName ="Order.txt";
File inputFile =new File(inputFileName);
FileInputStream in =new FileInputStream(inputFile);
BufferedReader iS =new BufferedReader(new InputStreamReader(in));
String iL ="";
iL = iS.readLine();
setDescription(iL);
iS.close();
}
catch(java.io.IOException ex){
System.out.println("Cannot read from file");
}
}
});
btnReturnToOrderSystem.addActionListener(new ActionListener(){
publicvoid actionPerformed(ActionEvent e){
setVisible(false);
//OrderSystem os = new OrderSystem();
//os.setVisible(true);
}
});
}
/** Set the text description */
publicvoid setDescription(String iL){
jta.getPreferredSize();
jta.setText(iL);
jta.append(iL);
}
publicstaticvoid main(String[] args){
new ViewOrder();
}
}
Probably here
String inputFileName = "Order.txt";
in combination with here:
catch(java.io.IOException ex){
System.out.println("Cannot read from file");
}
The file is not where you believe it is (relative path), and you take away your program's chance to tell you.
Frankly, people that "handle" exceptions like this deserve all the trouble they get.
Are you getting an IOException while trying to read the file ?
i am running my program from my USB stick. the text file is also on the USB stick. should i include code that changes the directory to "E:" in order to make sure that i'm reading the contents of the text file from the right directory? because the memory stick is mapped on the E drive on my computer. when i run my code i don't get any I/O exceptions at all.
First ensure you are able to select the file in an interactive manner...
Try this -
String inputFileName = null ;
JFileChooser fc = new JFileChooser();
int retValue = (fc.showOpenDialog(null));
if (JFileChooser.APPROVE_OPTION == retValue){
inputFileName = (fc.getSelectedFile().getAbsolutePath());
}
if (null == inputFileName){
System.out.println("Cannot find specified file");
throw new IOException();
return;
}
> First ensure you are able to select the file in an
> interactive manner...
I'd rather ensure that "file not found" is actually a problem by using a hard-coded absolute path first and then a normal resource-loading mechanism later, instead of changing the UI.
I'd also insert some debug printouts in the critical parts of the code to see if and how it's executed.
Harding coding paths can also be done. But generally using hard-coded paths leads down a one way street of having 'hidden' bugs. . resulting in the classic "But It works on my PC ...." scenario.
Also the file reading function given in the code does not look right....
Use this instead -
private void readFileContents(String selectedFile) {
try {
FileReader fileReader = new FileReader(selectedFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String tmp = null;
while ((tmp = bufferedReader.readLine() ) != null){
//System.out.println(tmp);
//Do your stuff here....
}
}catch (Exception ex){
ex.printStackTrace();
}
//close streams here...
}//readFileContents
> if (null == inputFileName){
>System.out.println("Cannot find specified file");
>throw new IOException();
>return;
This is quite bad code. (Does it actually compile?)
First, you're checking for something that's not supposed to happen: a file being selected and null being returned nevertheless. This would be a bug in the JFileChooser.
You might believe you're checking whether the file was deleted in the split-second between selection and retrieval, but that's not covered by this check - a File instance may exist without the corresponding file. Hence the File.exists() check. So you should rather check that, if you feel the need.
And if the file doesn't exist, it might be better to throw a FileNotFoundException with the appropriate information given, instead of printing some message to the console and throwing some generic and uninformative exception like "IOException" with no message set.
And the final return statement will never be reached.
Agreed from your perspective it is bad code. That is because you have not understood the complete code -
if (JFileChooser.APPROVE_OPTION == retValue){
inputFileName = (fc.getSelectedFile().getAbsolutePath());
}
The inputFileName is set only when the user clicks okay. Do refer to the documentation to convince yourself of the same. If the user clicks cancel we do not process the file.
Does it actually compile ? Well if you actually have a java compiler you can check for yourself ;-)
> Harding coding paths can also be done. But generally
> using hard-coded paths leads down a one way street of
> having 'hidden' bugs. . resulting in the classic "But
> It works on my PC ...." scenario.
We are doing error analysis here, not application design!
*sigh*
"Debugging can be done, but it slows down performance.."
And what's the point of adding a file chooser when all he wants to do is to load a resource? I for one don't know the use case, so I'm certainly not going to advocate changes in the application's design. If it makes sense, he may add it, but it doesn't help at all at the mement, especially *if* the file is found and the data gets lost elsewhere.
If you rather prefer to change your app instead of debugging to get rid of bugs, go ahead. But I'm sure you're pretty alone with that.
Just so that you know I'm okay with you referring to your 'constructive criticism' as error analysis.
> The inputFileName is set only when the user clicks
> okay. Do refer to the documentation to convince
> yourself of the same. If the user clicks cancel we do
> not process the file.
You're correct there - in this case you also commited the "crime" of throwing an exception for no reason, because it's not an exceptional condition that the user aborted an action.
> Does it actually compile ? Well if you
> actually have a java compiler you can check for
> yourself ;-)
I don't need a compiler to tell that it'll fail with "unreachable statement".
> Just so that you know I'm okay with you referring to
> your 'constructive criticism' as error analysis.
My criticism is about your code sample.
Error analysis is what we should be trying to do to find out why the OP's code fails.
There is no unreachable statement... there is however an error with the constructor of IOException
if (null == inputFileName){
System.out.println("Cannot find specified file");
//throw new IOException(""); //Agreed there is no need for this...
return;
}
My criticism is about your code sample.
Error analysis is what we should be trying to do to find out why the OP's code fails.
Well looks like for both the above points you still do need a compiler.....
> There is no unreachable statement...
throw new IOException();
return;
How would you call it?
System.out.println("Cannot find specified file");
There is no need for this either. First, the message should be "no file selected" which is entirely different from "not found", second, the user knows he didn't select a file. Third, your snippet has no program-usable output, although that of course can be modified by the OP.
I would suggest the OP to simply call exists() on the file to check whether he grabbed the right thing. Afterwards, depending on how that file is used, I'd suggest loading it as a resource.
Unreachable statement Touche.... Agreed, the exception needs to be commented.
System.out.println("Cannot find specified file"); - Agreed, wrong diagnostic.
File exists approach agreed....