【问题标题】:Getting path from exported jar not working从导出的 jar 获取路径不起作用
【发布时间】:2018-04-19 11:21:55
【问题描述】:

我在做什么:
我有一段代码,我在其中获取可运行路径并将其设置为按钮单击时的标签以进行测试,以便在运行时成功获取运行的 jar 路径。

问题:
通过 Eclipse 调试或运行模式运行时,我在标签中获取了路径,但是当我将代码导出到 jar 文件时,单击按钮时什么也没有发生。

代码:

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.File;
import java.net.URISyntaxException;

import javax.swing.JFrame;
import javax.swing.JPanel;

import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class TestProject extends JFrame {

    private JPanel contentPane;
    static JLabel lblNewLabel;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TestProject frame = new TestProject();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public TestProject() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout());
        setContentPane(contentPane);

        lblNewLabel = new JLabel("New label");
        contentPane.add(lblNewLabel, BorderLayout.CENTER);

        JButton btnNewButton = new JButton("New button");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                getJarFileRunningPath();

            }
        });
        contentPane.add(btnNewButton, BorderLayout.SOUTH);
    }

    public static String getJarFileRunningPath()
    {
        String currentPath = null;

        try
        {
            File currentFilePath = new File(TestProject.class.getProtectionDomain().
                                    getCodeSource().getLocation().toURI().getPath());

            currentPath = currentFilePath.getAbsolutePath();


            lblNewLabel.setText(currentPath);
        }
        catch (URISyntaxException e)
        {
        }

        return currentPath;
    }

}

更新:
我以某种方式发现“File currentFilePath = new File ...”行卡住了,也没有抛出异常。

感谢以后的任何帮助。 :-)

【问题讨论】:

  • 您是否尝试过远程调试以查看实际发生的情况?
  • 嗨吉姆,对不起,我不知道远程调试。 :-(

标签: java eclipse jar path


【解决方案1】:

我拿了你的代码来检查你的问题,但代码对我来说很好用。 生成的 jar 显示了标签中的路径。

我认为您的问题不是编码问题。

【讨论】:

  • 可能与操作系统版本有关。我正在找出答案。 :-(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-05
相关资源
最近更新 更多