Java 如何使用.jar文件之外的localfile设置JEditorPane的页面()?
我的程序在.jar文件中有以下路径Java 如何使用.jar文件之外的localfile设置JEditorPane的页面()?,java,jeditorpane,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
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”)代码>被调用文件在测试
包中搜索文件时未找到该文件。
如何setPage()
temp.htm
文件,该文件位于.jar
文件之外,但与.jar
文件位于同一文件夹中?因为
temp.htm
是一个本地文件,我想要一个相对路径而不是绝对路径
谢谢。您不能将.java文件用作类路径。您只能将路径(相对或绝对)或JAR文件放入类路径。只要将临时文件写入的路径是类路径的一部分,它就应该可以使用
editorPane.setPage(Program.class.getResource("temp.htm"));
正如你所写
换句话说,在使用之前
file.createNewFile();
您需要确保
文件是类路径中列出的目录。您可以尝试以下操作:
// 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();
}
//获取代码源的位置
URL URL=yourpackage.Main.class.getProtectionDomain().getCodeSource().getLocation();
试一试{
//从源代码url中提取目录
字符串根=(新文件(url.toURI()).getParentFile().getPath();
文件doc=新文件(根,“test.htm”);
//为测试创建htm文件内容
FileWriter writer=新的FileWriter(文档);
编写(“测试”);
writer.close();
//在编辑器中打开它
editor.setPage(doc.toURI().toul());
}捕获(例外e){
e、 printStackTrace();
}
创建.jar文件后,是否可以在classpath@Jaguar:如果您拥有该目录的访问权限,它应该可以工作。但是该目录将不存在,现在只有jar文件存在。目录将在jar文件中,在这种情况下,可以在jar中写入吗file@Jaguar:是否要在JAR文件中创建目录?我认为这是行不通的,因为JVM会锁定JAR文件。您需要在用户的家中的某个地方创建一个目录。这样,避免访问限制的机会就更大了。创建目录后,需要创建一个新的URLClassLoader
,其中包含所需的所有类路径条目。然后可以使用该实例对其调用getResource()
。