JAR包命令行运行正常,双击启动无法加载数据问题求助
问题:双击JAR包无法加载文本与图片,命令行及IDE运行正常
我开发了一款Java桌面应用,需读取文本文件、显示JPEG图片。该应用在NetBeans中运行正常,将JAR包移至非NetBeans目录后,通过命令行执行java -jar <myfile.jar>也能正常运行,但双击JAR包图标时,仅能打开GUI界面,本该显示数据的字段为空,图片也无法加载。
我曾按其他帖子建议,将代码从FileReaders、FileWriters改为使用IOStreams实现,但问题依旧:NetBeans及命令行运行均正常,双击JAR仅显示无数据的GUI。
我查阅过类路径(classpath)相关资料,但疑惑若为类路径问题,命令行运行也应出现异常。
简化后的代码
package com.steve; import javax.swing.*; import java.awt.*; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.charset.StandardCharsets; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; public class Testing extends JFrame{ public Testing(){ super("My Test App"); EntryPanel panel = new EntryPanel(); this.getContentPane().add(panel); this.setSize(800, 600); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } public class EntryPanel extends JPanel{ String strTextToDisplay; public EntryPanel(){ super(); try{ this.strTextToDisplay = getTextFromFile(); } catch(IOException ioe){ System.out.println(ioe.getMessage()); } } private String getTextFromFile() throws IOException{ String fileName = "testfile.txt"; var filePath = Paths.get(fileName); String myStr = "Here it is:\n"; try(BufferedReader br = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)){ String line; while((line = br.readLine()) != null){ myStr = myStr.concat(line).concat("\n"); } } System.out.println(myStr); return myStr; } @Override public void paintComponent(Graphics g){ g.setColor(new Color(0, 0, 255)); g.fillRect(0,0, this.getWidth(), this.getHeight()); g.setColor(new Color(255, 100, 100)); g.setFont(new Font("Serif", Font.BOLD, 15)); g.drawString(strTextToDisplay, 20, 20); } } public static void main(String[] args){ System.out.println("In main"); Testing myTest = new Testing(); } }
manifest.txt文件内容
Manifest-Version: 1.0 Class-Path: com.resources/testfile.txt Main-Class: com.steve.Testing Created-By: 21.0.10 (Ubuntu)
内容的提问来源于stack exchange,提问作者Steve Baker
相关产品推荐
相关产品推荐

