简体   繁体   English

为什么此Java代码不起作用?

[英]Why doesn't this java code work?

What I want to do is very basic: I have an interface that contains a button; 我想做的事情非常基础:我有一个包含按钮的界面; when I push that button, I want my program to read the next line from a text file and display it in a textfield. 当我按下该按钮时,我希望程序从文本文件中读取下一行并将其显示在文本字段中。 But nothing happens, and I have a feeling it's because it doesn't read my file correctly :\\ Please help, I'm a complete newbie in the Java world and I was even happy that I got rid of the compiler errors (yay me!) but this is worse, 'cause now I don't know what to google :)) 但是什么也没发生,我感觉是因为它无法正确读取我的文件:\\请帮助,我是Java世界中的一个完全新手,我甚至很高兴摆脱了编译器错误(是的, !)但情况更糟,因为现在我不知道该怎么用Google :))

package practice;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;

public class MyApp extends JFrame {
    JButton button;
    JTextArea afisaj; 

    MyApp(){ 
        setTitle("MyApp");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        init();
        setSize(500,500);
        setLocationRelativeTo(null); 
        setVisible(true); 
    }

    public void init(){
        this.setLayout(null);

        button = new JButton("Read more");
        afisaj = new JTextArea();

        button.setBounds(200,50,100,30); 
        add(button); 

        afisaj.setBounds(40,100,400,300);
        add(afisaj); 
    }

public static void main(String[] args){
    final MyApp m = new MyApp(); 

    File f = new File("C:\\myfile.txt");
    BufferedReader b = new BufferedReader(new InputStreamReader(System.in));   
    try{
    b = new BufferedReader(new FileReader(f));  
    }
    catch (FileNotFoundException e){System.out.println("error 1")}

    final BufferedReader bf = b; 

      m.button.addActionListener(new ActionListener(){     
      public void actionPerformed(ActionEvent e){
          String s = new String();        
          try{
                if ((s=bf.readLine())!= null){
                    m.afisaj.append(s);  
                }
            }
            catch (Exception ee){System.out.println("error 2")}   
      }      
    }); 

    try{
    bf.close(); 
    }
    catch (Exception e1){System.out.println("error 3")}; 

}

}

The problem is that the stream you define get closed in try block. 问题是您定义的流在try块中被关闭了。 So when you try to read it gives Stream is closed. 因此,当您尝试阅读时,它会关闭Stream。

1、data can not be shared,bf in the click event does not get to the 1,数据无法共享,bf在点击事件中没有到达

final BufferedReader bf = b; 

2、Code is modified as follows to achieve your results 2,代码修改如下,以达到您的效果

public static void main(String[] args) {
    final MyApp m = new MyApp();
    m.button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            File f = new File("C:\\myfile.txt");
            BufferedReader b = new BufferedReader(new InputStreamReader(
                    System.in));
            try {
                b = new BufferedReader(new FileReader(f));
            } catch (FileNotFoundException ee) {
            }

            String s = new String();
            try {
                while ((s = b.readLine()) != null) {
                    m.afisaj.append(s);
                }
                b.close();
            } catch (Exception ee) {
            }
        }
    });
}

You should close the stream, when you close the window. 关闭窗口时,应关闭流。 Now you close it after you registered the event listener for the button. 现在,在为按钮注册事件侦听器后将其关闭。 And before you really press the button. 在您真正按下按钮之前。

public static void main(String[] args) throws Exception {
  final MyApp m = new MyApp();

  File f = new File("myfile.txt");
  BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
  b = new BufferedReader(new FileReader(f));

  final BufferedReader bf = b;

  m.button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      String s = new String();
      try {
        if ((s = bf.readLine()) != null) {
          m.afisaj.append(s);
        }
      } catch (Exception ex) {
        throw new RuntimeException(ex);
      }
    }
  });

  m.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent e) {
      try {
        bf.close();
      } catch (Exception ex) {
        throw new RuntimeException(ex);
      }
    }
  });
}

And please stop swalowing exception. 并且,请不要再拖延异常。 System wouls have told you, that stream is closed and the rest is very simple, once you have that information! 系统会告诉您,一旦您掌握了这些信息,流就关闭了,其余的非常简单!

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

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