0

我的程序在 .jar 文件中有以下路径
src/test/Program.class

我的程序如下...

Program.java

package test;
import java.io.File;
import java.io.IOException;
import javax.swing.JEditorPane;
import javax.swing.JFrame;

public class Program {

    JEditorPane editorPane;
        public Program() {
        File file = new File("temp.htm");
        try {
            file.createNewFile();
            editorPane = new JEditorPane();
            editorPane.setPage(Program.class.getResource("temp.htm"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public JEditorPane getEditorPane(){
        return editorPane;
    }
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setVisible(true);
        Program p = new Program();
        frame.getContentPane().add(p.getEditorPane());
    }
}

问题是我已经在一个.jar文件中编译了程序。
在文件外部file.createNewFile();创建文件 所以当被调用时找不到文件,因为它在包内搜索文件。 如何在文件之外但与文件位于同一文件夹中的文件? 因为这是一个本地文件,我想要一个相对路径而不是绝对路径。 temp.htm.jar
editorPane.setPage(Program.class.getResource("temp.htm"));test
setPage()temp.htm.jar.jar
temp.htm

谢谢。

4

2 回答 2

2

您可以尝试以下方法:

// get location of the code source
URL url = yourpackage.Main.class.getProtectionDomain().getCodeSource().getLocation();

try {
    // extract directory from code source url
    String root = (new File(url.toURI())).getParentFile().getPath();
    File doc = new File(root, "test.htm");
    // create htm file contents for testing
    FileWriter writer = new FileWriter(doc);
    writer.write("<h1>Test</h1>");
    writer.close();
    // open it in the editor
    editor.setPage(doc.toURI().toURL());
} catch (Exception e) {
    e.printStackTrace();
}
于 2010-12-26T19:15:18.250 回答
0

您不能使用 .java 文件作为类路径。您只能将路径(相对或绝对)或 JAR 文件放入类路径。只要您将临时文件写入的路径是类路径的一部分,它就应该与

editorPane.setPage(Program.class.getResource("temp.htm"));

正如你所写。

换句话说,在你使用之前

file.createNewFile();

您需要确保这file是类路径中列出的目录。

于 2010-12-26T18:28:26.207 回答