I have the following method which will launch and load a page an HTML page in the default browser:
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");
}
It works fine but I want to make it more versatile, meaning if I move the file it won't break the link. I have moved the file to the directory of the project so when I move the project the HTML page moves with it. How can I do such a thing?
EDIT : updated code
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");
}
Url output : C:\\Users\\Steve\\Google Drive\\Higher National Diploma 1\\Semester 1\\Assignments\\Object Oriented Programming (Java)\\Steve_Azzopardi_HND3\\help\\lotto.html
Exception stack trace : java.net.URISyntaxException: Illegal character in opaque part at index 2: C:\\Users\\Steve
You could put it in the classpath ( best solution in my opinion ). But you can also do this in java:
String currDir = new File("").getAbsolutePath(); //project directory
Put the file in a directory you would like to use, for example the project directory itself. Put the html file there, and if you move your project you move it too.
But I think you want to create a html folder inside the directory:
project_path/help/lotto.html
Then you can load it like this:
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");
}
Put your resource in the classpath so that your path address becomes the path of the file in your working directory. I think that should solve it completely.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.