如何设置Page()一个JEditorPane与一个在.jar文件之外的本地文件?

时间:2010-12-26 18:11:23

标签: java jeditorpane

我的程序在.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是本地文件,我想要一个相对路径而不是绝对路径。

感谢。

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:0)

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

一起使用
editorPane.setPage(Program.class.getResource("temp.htm"));

正如你所写的那样。

换句话说,在使用之前

file.createNewFile();

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