我有以下方法在默认浏览器中启动并加载页面HTML页面:
try {
String url = "file:///C:/Users/Steve/Google%20Drive/Higher%20National%20Diploma%201/Semester%201/Assignments/Object%20Oriented%20Programming%20(Java)/Steve_Azzopardi_HND3/help/lotto.html";
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(url));
} catch (Exception ex) {
System.out.println("Help file was not found");
}
它工作正常,但我想让它更通用,这意味着如果我移动文件它不会打破链接。我已将文件移动到项目目录中,因此当我移动项目时,HTML页面随之移动。我怎么能这样做?
编辑: 更新的代码
try {
String url = new File("help/lotto.html").getAbsolutePath();
System.out.println(url);
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(url));
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("Help file was not found");
}
网址输出:C:\ Users \ Steve \ Google Drive \ Higher National Diploma 1 \ Semester 1 \ Assignments \ Object Oriented Programming(Java)\ Steve_Azzopardi_HND3 \ help \ lotto.html
异常堆栈跟踪:java.net.URISyntaxException:索引2处的不透明部分中的非法字符:C:\ Users \ Steve
答案 0 :(得分:1)
你可以把它放在类路径中(在我看来是最好的解决方案)。但您也可以在java中执行此操作:
String currDir = new File("").getAbsolutePath(); //project directory
将文件放在您想要使用的目录中,例如项目目录本身。将html文件放在那里,如果移动项目,也可以移动它。
但我想你想在目录中创建一个html文件夹:
project_path /帮助/ lotto.html
然后你可以像这样加载它:
try {
File f = new File("help/lotto.html");
URI uri = f.toURI();
Desktop desktop = Desktop.getDesktop();
desktop.browse(uri);
} catch (Exception ex) {
System.out.println("Help file was not found");
}
答案 1 :(得分:0)
将您的资源放在类路径中,以便您的路径地址成为工作目录中文件的路径。我认为应该完全解决它。