尝试添加一些关于我的项目的信息,这是我的代码:
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();
答案 0 :(得分:0)
它不起作用,因为从ClassLoader
和相对于类文件加载类之间存在语义差异:
ClassLoader.getResource()
将尝试从类路径加载类,但如果文件存在于JAR文件中,则不会加载Class.getResource()
将尝试相对于类文件加载类,即使它是JAR文件的一部分IDE通常从目录而不是JAR文件执行代码。您需要使用以下代码:
File fileChange = new File(getClass().getResource("changelog.txt").getFile());