private void jtext1ActionPerformed(java.awt.event.ActionEvent evt)
{
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
try
{
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
jtext1.read(br, null);
br.close();
jtext1.requestFocus();
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
我在为应用程序创建功能时尝试在JButton中运行此代码,并不断收到错误消息:
找不到符号symbol:方法read(bufferedreader,)位置:jbutton类型的变量jtext1
答案 0 :(得分:0)
由于从read()
调用JButton
方法而收到该错误,但是按钮不读取文件-它们所做的只是单击事件时引发事件,因此您可以运行其他代码作为响应。
您应该做的是在read()
上呼叫br
上的BufferedReader
。我不确定为什么要尝试将BufferedReader的实例传递给它自己,但是这些不是read()
所采用的参数。即使您在正确的对象上调用了该方法,它也会因其他错误而失败。
通常,您将使用readLine()
方法,顾名思义,该方法读取整行文本,从而使您可以逐行处理文件而不必告诉代码多少字节的内容。每次读取要处理的数据。
您想要执行以下操作:
private void jtext1ActionPerformed(java.awt.event.ActionEvent evt)
{
// Your FileChooser code should live in a separate method. If the user
// selects the FileChooser from a menu, then create an event handler for
// that menu item.
try
{
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
String line = "";
while((line = br.readLine()) != null)
{
// Do whatever you want with the line.
// You can add it to an arraylist
// or you can split() it into parts
// or you can just print it to screen. Whatever.
}
br.close();
// this line is probably unnecessary, but ultimately, not harmful
jtext1.requestFocus();
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}