开发者

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

My p开发者_如何学运维rogram 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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜