1

试图添加一些关于我的项目的信息,这是我的代码:

import java.awt.EventQueue;

public class InfoView extends JDialog {

ClassLoader classLoader = this.getClass().getClassLoader();
File fileChange = new File(classLoader.getResource("changelog.txt").getFile());
File fileTodo = new File(classLoader.getResource("TODO.txt").getFile());
File filePoradnik = new File(classLoader.getResource("Poradnik.txt").getFile());
File file;

public InfoView(JFrame frame, boolean b, int a) {
    setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    setModal(b);

    setMinimumSize(new Dimension(200, 100));
    setBounds(100, 100, 450, 300);
    getContentPane().setLayout(new GridLayout(0, 1, 0, 0));

    JTextArea txtchangelog = new JTextArea();
    txtchangelog.setEditable(false);
    txtchangelog.setFont(new Font("Monospaced", Font.PLAIN, 13));
    JScrollPane sp = new JScrollPane(txtchangelog);   
    getContentPane().add(sp);

    switch(a){
    case 0:
        file=filePoradnik;
        break;
    case 1:
        file=fileTodo;
        break;
    case 2:
        file=fileChange;
        break;
    }   

    try
    {
        FileReader reader = new FileReader(file);
        BufferedReader br = new BufferedReader(reader);
        txtchangelog.read( br, null );
        br.close();
        txtchangelog.requestFocus();
        reader.close();
    }
    catch(Exception e2)
    { System.out.println(e2); }
    //setVisible(true);
    repaint();
}

问题是在eclipse中工作时它可以工作,但是当我制作jar文件时它不会...... Agr没有找到任何解决方案......

出了什么问题....试图读取 jar 中的文件....


我想我找到了。。

  ClassLoader classLoader = this.getClass().getClassLoader();
  InputStream fileChange =classLoader.getResourceAsStream("changelog.txt");
   InputStream fileTodo = classLoader.getResourceAsStream("TODO.txt");
   InputStream filePoradnik =classLoader.getResourceAsStream("Poradnik.txt");
   InputStream file;
   BufferedReader br = new BufferedReader(new InputStreamReader(file));
   txtchangelog.read( br, null ); br.close(); 
  txtchangelog.requestFocus();
    file.close();
4

1 回答 1

0

It does not work because there is a semantic difference between loading classes from a ClassLoader and relatively to a class file:

  1. ClassLoader.getResource() will try to load class from the classpath, but if the file exists in the JAR file, it will not be loaded
  2. Class.getResource() will try to load class relatively to a class file even if it is part of JAR file

IDEs generally execute code from directories and not JAR files. You need to use the following code:

File fileChange = new File(getClass().getResource("changelog.txt").getFile());
于 2015-04-02T16:34:01.733 回答