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

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();

最佳答案

它不起作用,因为从ClassLoader加载类和相对于类文件加载类之间存在语义差异:


ClassLoader.getResource()会尝试从类路径中加载类,但是如果该文件存在于JAR文件中,则不会加载
Class.getResource()将尝试相对于类文件加载类,即使它是JAR文件的一部分


IDE通常从目录而不是JAR文件执行代码。您需要使用以下代码:

File fileChange = new File(getClass().getResource("changelog.txt").getFile());

10-08 16:01