【问题标题】:How to setPage() a JEditorPane with a localfile which is outside of the .jar file?如何使用 .jar 文件之外的本地文件 setPage() 一个 JEditorPane?
【发布时间】:2010-12-27 03:15:18
【问题描述】:

我的程序在.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();.jar 文件外创建temp.htm 文件
因此,当调用 editorPane.setPage(Program.class.getResource("temp.htm")); 时,找不到文件,因为它在 test 包内搜索文件。
如何setPage()temp.htm 文件位于.jar 文件之外但与.jar 文件位于同一文件夹中?
由于temp.htm 是一个本地文件,我想要一个相对路径而不是绝对路径。

谢谢。

【问题讨论】:

    标签: java jeditorpane


    【解决方案1】:

    你可以试试这样的:

    // 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();
    }
    

    【讨论】:

      【解决方案2】:

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

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

      正如你所写。

      换句话说,在你使用之前

      file.createNewFile();
      

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

      【讨论】:

      • 在我制作 .jar 文件后,是否可以在类路径中列出的目录中创建文件
      • @Jaguar:如果您拥有该目录的访问权限,它应该可以工作。
      • 但该目录将不存在,现在只有jar文件存在。并且目录将在jar文件中
      • 在这种情况下是否可以在jar文件中写入
      • @Jaguar:你想在 JAR 文件中创建一个目录吗?我认为这不会起作用,因为 JVM 会锁定 JAR 文件。您需要在用户家中的某处创建一个目录。这样,避免访问限制的机会就更高。创建目录后,您需要创建一个新的URLClassLoader,其中包含您需要的所有类路径条目。然后,您可以使用该实例在其上调用 getResource()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-28
      • 1970-01-01
      • 2018-01-07
      • 1970-01-01
      • 1970-01-01
      • 2010-10-02
      相关资源
      最近更新 更多