jesric1029 jesric1029 - 4 months ago 34
Java Question

Using process builder to open a file in internet explorer Java

I have a program I have written for Java at work that takes an XML and allows users to view the XML in table form, make changes, then save the table as a new XML.

Everything is finished except one small detail. Once the user saves the table the data is of course parsed into a new XML. I then want a dialog to appear that tells the user the save location and asks if they would like to open the file.

If the user clicks yes then I want the XML to open in Internet Explorer. I had successfully implemented a similar approach with ProcessBuilder in another program but in that case the file needed to open with Notepad which worked perfectly.

Now the issue I'm having is that while InternetExplorer will open the file will not open, the browser will just stay on the home page. I'll post my code below if anyone can help me I'd greatly appreciate it!

location = "//CamT54Revised"+date+".xml";
location = fHandling.saveFile.getSelectedFile()+location;

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(location));
transformer.transform(source, result);

int dialogResult = JOptionPane.showConfirmDialog(null, "Output file saved as "+location+". Would you like to view the file?","Display Output",JOptionPane.YES_NO_OPTION);
if(dialogResult==JOptionPane.YES_OPTION){

ProcessBuilder pb = new ProcessBuilder("C:\\Program Files\\Internet Explorer\\iexplore.exe", location);
try{
pb.start();
}catch(IOException e){
e.printStackTrace();
}

}

Answer

Supposing that Internet Explorer is the default browser, you can use Desktop API for that matter.

public class DesktopTest {

    public static void main(String args[]) {

        if (!Desktop.isDesktopSupported()) {
            System.err.println("Desktop not supported!");
            System.exit(-1);
        }

        Desktop desktop = Desktop.getDesktop();
        File file = new File(args[0]);

        if (desktop.isSupported(Desktop.Action.OPEN)) {
            try {
                desktop.open(file);
            }
            catch (IOException ioe) {
                System.err.println("Unable to open: " + file.getName());
            }
        }
    }
}

But if you want to actually force Internet Explorer, then you will probably have to resort to your process builder anyways.