How to setPage() a JEditorPane with a localfile which is outside of the .jar file?

微笑、不失礼 提交于 2019-12-11 18:46:54

问题


My program has the following path in the .jar file
src/test/Program.class

and my program is as follow...

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

The problem is that I have compiled the program in a .jar file.
The file.createNewFile(); creates the temp.htm file outside the .jar file
So when editorPane.setPage(Program.class.getResource("temp.htm")); is called the file is not found as it searches for file inside the test package.
How to setPage() the temp.htm file whiich is outside the .jar file but in the same folder as the .jar file?
As the temp.htm is a localfile and I want a relative path instead of an absolute path.

Thanks.


回答1:


You could try something like:

// 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:


You cannot use a .java-file as the classpath. You can only put paths (relative or absolute) or JAR-files into the classpath. As long as the path where you write the temporary file to is part of the classpath, it should work with

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

as you wrote.

In other words, before you use

file.createNewFile();

you need to make sure that file is a directory listed in the classpath.



来源:https://stackoverflow.com/questions/4534881/how-to-setpage-a-jeditorpane-with-a-localfile-which-is-outside-of-the-jar-fil

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!