12

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.

hippietrail
  • 15,848
  • 18
  • 99
  • 158
Jeff C
  • 445
  • 4
  • 10

5 Answers5

4

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!

memnoch_proxy
  • 1,944
  • 15
  • 20
1

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.

0

For Windows only, you could try

System.exec("cmd.exe start file:///C:/foo/bar.html#anchor")
Lawrence Dol
  • 63,018
  • 25
  • 139
  • 189
0

I've done some investigation on this item here - note that opening cmd and typing start file:///c:/temp/test.html#anchor also doesn't work.

I think the only thing that actually works is to call a browser manually (or use a third-party tool that does this).

On Windows, you always have Internet Explorer, so you could call Runtime.getRuntime().exec("cmd.exe start iexplore " + myURL) if you really don't want to find iexplore.exe yourself - but this doesn't always work either.

Community
  • 1
  • 1
Adam Rofer
  • 6,121
  • 1
  • 14
  • 11
0

You could try using BrowserLauncher2. It's a small and self-contained cross-platform library to open the default browser. It handles anchors perfectly.

amarillion
  • 24,487
  • 15
  • 68
  • 80
  • Doesn't work for me in Windows 7, the anchor is stripped. I think it's an OS issue, ProcessMonitor shows my call to Firefox without the anchor. – glenneroo Jun 21 '17 at 12:02
  • While this might be a valuable hint to solve the problem, a good answer also demonstrates the solution. Please [edit] to provide example code to show what you mean. Alternatively, consider writing this as a comment instead. – Toby Speight Jun 21 '17 at 12:11