简体   繁体   English

使用JFrame和BufferedReader获取文件内容

[英]Getting file contents using JFrame and BufferedReader

the code bellow it is a part of my code. 下面的代码是我代码的一部分。

The problem in "Generate Keys.." button doesn't give any thing on the text area!. “ Generate Keys ..”按钮中的问题在文本区域没有任何作用!

I think the buffered reader cannot get the file path.. i don't know why?! 我认为缓冲的阅读器无法获取文件路径。。我不知道为什么?!

   public class Finding_Candidate_Keys {   

  static String L[];
  static int size;
  static JFrame frame;
  static JTextArea textArea;
  static String     TextAreaContent = "";
  static File selectedFile;
  static String filePath;
  static JFileChooser fileChooser = new JFileChooser();
  static File file;


  static void displayJFrame()
  {
     frame = new JFrame("Advanced DB Project- Key Definition");
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     textArea = new JTextArea("");
     textArea.setSize(250,250);    
     textArea.setEditable(false);
     textArea.setVisible(true);
     JScrollPane scroll = new JScrollPane(textArea);
     scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
     scroll.setPreferredSize(new Dimension(350, 350));
     frame.add(scroll);
     frame.setVisible(true);

     JButton button = new JButton("Select File");

     button.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {

            textArea.setText("");
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files (*.txt)", "txt");
            fileChooser.setFileFilter(filter);


                           int returnValue = fileChooser.showOpenDialog(frame);


                if (returnValue == JFileChooser.APPROVE_OPTION)  
                {
                    if (fileChooser.getSelectedFile() != null) {
                    selectedFile = fileChooser.getSelectedFile();
                    filePath = selectedFile.getAbsolutePath();
                    file = new File (filePath);

                    textArea.append("Opening: " + selectedFile.getName() +  "\n");              
                    }
                } 
        else {
            textArea.setText("");
            textArea.append("Open command cancelled by user." +  "\n");
             }

          }
     });

      frame.setVisible(true);

              //********************
     JButton showDialogButton = new JButton("Generate Keys..");

     showDialogButton.addActionListener(
           new ActionListener()
           {
              public void actionPerformed(ActionEvent e)
              {
                 textArea.setText("");
                 textArea.append(TextAreaContent);
              }
           });

           frame.add(showDialogButton);
           frame.setVisible(true);

     //*********************

     frame.getContentPane().setLayout(new FlowLayout());
     frame.getContentPane().add(button);
     frame.setPreferredSize(new Dimension(500, 500));
     frame.setSize(400,460);
     frame.setLocationRelativeTo(null);
     frame.pack();
     frame.setVisible(true);   
  }

  public static void main(String[] args) throws IOException{    
     SwingUtilities.invokeLater(
           new Runnable()
           {
              public void run()
              {
                 displayJFrame();
              }
           });

     BufferedReader br = new BufferedReader(new FileReader(filePath));
     .
     .
     .

Note that : it is work properly if i use the name of the file directly like: 请注意:如果我直接使用文件名,例如:

BufferedReader br = new BufferedReader(new FileReader("input.txt"));

insted of 装的

BufferedReader br = new BufferedReader(new FileReader(filePath));

can any one told me where is the mistake ? 谁能告诉我错误在哪里?

also this appear during the run: 在运行过程中也会出现:

Exception in thread "main" java.lang.NullPointerException
at java.io.FileInputStream.<init>(FileInputStream.java:124)
at java.io.FileInputStream.<init>(FileInputStream.java:87)
at java.io.FileReader.<init>(FileReader.java:58)
at Finding_Candidate_Keys.main(Finding_Candidate_Keys.java:110)

You never initialize your filePath member variable. 您永远不会初始化filePath成员变量。 Because of this it will be initialized to null , which is the default value for member objects. 因此,它将被初始化为null ,这是成员对象的默认值。 Since it will be set to null , the constructor of FileReader will throw a NullPointerException . 由于将其设置为null ,因此FileReader的构造函数将抛出NullPointerException You could solve this by initializing your variable: 您可以通过初始化变量来解决此问题:

String filePath = "input.txt";

EDIT: 编辑:

As noted in the comments, you seem to initialize it in a conditional statement in your displayJFrame method. 如注释中所述,您似乎在displayJFrame方法的条件语句中对其进行了初始化。 This method is invoked by the runnable passed to SwingUtilities.invokeLater . 传递给SwingUtilities.invokeLater的runnable调用此方法。 As the name implies, this method will not run the Runnable passed to it directly, but will execute it on another thread later on. 顾名思义,此方法将不会直接运行传递给它的Runnable ,而是稍后将在另一个线程上执行它。 Thus you value will not be initialized, since your method call will most likely run after you use the value in your main method. 因此,您的值将不会初始化,因为您的方法调用很可能会在您在main方法中使用该值后运行。 You will have to wait until the method is completed, a possible solution is to use the function SwingUtilities.invokeAndWait instead of SwingUtilities.invokeLater . 您将不得不等待该方法完成,一种可能的解决方案是使用函数SwingUtilities.invokeAndWait而不是SwingUtilities.invokeLater This method will wait for the call to finish. 此方法将等待调用完成。

You are getting no text because you have set it to show no text . 您没有收到任何文本,因为您已将其设置为不显示任何文本 Here is how, in your action listener for Generate Keys.. button: 这是在您的动作侦听器中的“ Generate Keys..按钮的方式:

textArea.setText("");
textArea.append(TextAreaContent);

And your TextAreaContent in initialized with empty string, in the initialization section of your class: 然后在类的初始化部分中,用空字符串初始化TextAreaContent

...
static String TextAreaContent = "";
...

Set TextAreaContent to have something that you want to see. TextAreaContent设置为您想要看到的内容。 For example, you could do something like this: 例如,您可以执行以下操作:

if (returnValue == JFileChooser.APPROVE_OPTION) {
    if (fileChooser.getSelectedFile() != null) {
        selectedFile = fileChooser.getSelectedFile();
        filePath = selectedFile.getAbsolutePath();
        file = new File(filePath);

        textArea.append("Opening: " + selectedFile.getName() + "\n");
        TextAreaContent = "You have selected some file: " + selectedFile.getName();
    }
} else {
     textArea.setText("");
     textArea.append("Open command cancelled by user." + "\n");
     TextAreaContent = "You chose no file";
}

As for the error, due to invokeLater method, the displayJFrame method is executed asynchronously on another thread, and the next line is executed in the main thread. 对于错误,由于invokeLater方法, displayJFrame方法在另一个线程上异步执行,而下一行在主线程中执行。 During the execution of the last line, the filePath is still may not be initialised, causing the error. 在执行最后一行的过程中, filePath可能仍未初始化,从而导致错误。 To remove the error, you could do this check: 要消除该错误,您可以执行以下检查:

if (filePath != null) {
    BufferedReader br = new BufferedReader(new FileReader(filePath));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM