Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to launch a file protocol URL with an anchor from Java?

From a Java program, I need to launch the default browser on a local HTML file, pointed to an anchor inside the file. In Java SE 6, the java.awt.Desktop.browse method will open the file, but will not honor the anchor, so something like the following opens the file at the top, but does not page the browser to the anchor:

Desktop.getDesktop("file:///C:/foo/bar.html#anchor");

Sun says here http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6477862 that anchors are not supported in the file URI protocol.

Does anyone have a better answer?

I can use Java SE 6. I would be OK with a Windows only solution.

like image 914
Jeff C Avatar asked Nov 18 '08 23:11

Jeff C


2 Answers

I just solved this another way, because no amount of quoting or spaces in any of these examples worked for me.

1 Detect if the file URI has a anchor or query string

2 If so, create a temp file File tmpfile = File.createTempFile("apphelp", ".html") with a meta-redirect to the actual file URI I desire:

<html><head>
<meta http-equiv="refresh" content="0;url=help.html#set_filter" />
</head></html>

3 Execute the local rundll command using new temporary URI:

Runtime.getRuntime().exec(
  "rundll32 url.dll,FileProtocolHandler \"" 
  +tmpfile.toURI().toString()+ "\"");

I hope this works for you!

like image 59
memnoch_proxy Avatar answered Oct 21 '22 17:10

memnoch_proxy


Solution on Windows is:

rundll32 URL.dll, FileProtocolHandler "file:///x:/temp/fragtest.htm#frag"

Mind the quotes!!!

rundll32 URL.dll, FileProtocolHandler file:///x:/temp/fragtest.htm#frag does work as expected.

like image 44
Helmut Reis Avatar answered Oct 21 '22 17:10

Helmut Reis