Linking to Open a file in java

Hello,
I wanted to create a link in my program that opens an excel spread sheet, seperately from the program. (i.e opens in excel). Is it possible to do this?
Thanks
Stu
Message was edited by:
studomonly

import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.*;
class OpenExcelDemo {
    public static void main(String[] args) {
        new OpenExcelDemo().go();
    void go() {
        JFileChooser jfc = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel Files", "xls", "csv");
        jfc.setFileFilter(filter);
        int returnVal = jfc.showOpenDialog(null);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
           open(jfc.getSelectedFile());
    private void open(File f) {
        String[] commands = {
            "rundll32",
            "url.dll,FileProtocolHandler",
            f.getAbsolutePath()
        try {
            Runtime.getRuntime().exec(commands);
        } catch (IOException e) {
            e.printStackTrace();
}All normal caveats apply.
~

Similar Messages

  • How to open/read file using Java in Unix?

    Hi Friends,
    Can you please help me out how to open/read file using java in unix os? I have create one text file in "/home/test.txt" in unix environment. How to open the same file & read using java code?
    - Hiren Modi

    http://java.sun.com/docs/books/tutorial/essential/io/index.html

  • Open servlet file from java

    can i open servlet file from java

    do you mean linking to a servlet from java application?
    have you try this?
    URL toServlet = new URL("URLtoServlet");
    URLConnection servletConnection = toServlet.openConnection();

  • Open a file using java......... how?

    hi all
    I have a prob with my code
    the problem is by using the FileChooser like
    file = fileChooser.getSelectedFile();
    I have the file name but how can i open that file e.g. if file is word document then that file should open in word , if that file is HTML file then open in IE , and other files as well.
    is there any way to open a file
    plz help me
    Thanx
    Regards
    Satinderjit

    veer ji, try this code on your pc if you can. Click the print button and see that happens. thanx yuvraj:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    //import com.sun.java.swing.*;
    import javax.swing.*;
    public class ComponentPrinterFrame
    extends JFrame
    implements Printable {
    public static void main(String[] args) {
    ComponentPrinterFrame cpf = new ComponentPrinterFrame();
    cpf.setVisible(true);
    public ComponentPrinterFrame() {
    super("ComponentPrinterFrame v1.0");
    createUI();
    protected void createUI() {
    JPanel panel = new JPanel();
    JButton printButton = new JButton("Print");
    panel.add(printButton);
    panel.add(new JList(new Object[] { "One", "Two", "Three" }));
    panel.add(new JButton("Push me"));
    panel.add(new JCheckBox("Chess", true));
    panel.add(new JComboBox(new Object[] { "Eins", "Zwei", "Drei" }));
    printButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    PrinterJob pj = PrinterJob.getPrinterJob();
    pj.setPrintable(ComponentPrinterFrame.this);
    if (pj.printDialog()) {
    try { pj.print(); }
    catch (PrinterException pe) {
    System.out.println(pe);
    setContentPane(panel);
    setSize(400, 400);
    // Center.
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize = getSize();
    int x = (screenSize.width - frameSize.width) / 2;
    int y = (screenSize.height - frameSize.height) / 2;
    setLocation(x, y);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    dispose();
    System.exit(0);
    public int print(Graphics g, PageFormat pf, int pageIndex) {
    if (pageIndex != 0) return NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D)g;
    g2.translate(pf.getImageableX(), pf.getImageableY());
    getContentPane().paint(g2);
    return PAGE_EXISTS;

  • Link to open pdf file in new window

    I want to create a link on a web page to open a pdf file in a
    new window. I used the "on click" "open brower window". Which does
    open the pdf file, but not in a new window. How do I open it in a
    new window?

    Your code is a mess:
    ** there is no apparent reason for the span:
    <td><span class="style1"
    onfocus="MM_openBrWindow('pdf/PR_launch.pdf','','')">Milford, OH
    So change that line to:
    <td>Milford, OH
    ** here you have two double quotes before This.
    <a title="”This" class="pdfFile"
    onclick="MM_openBrWindow('pdf/PR_Launch.pdf','','')"
    Change it to this, (with some other improvements):
    <a title="This" class="pdfFile"
    onclick="MM_openBrWindow(this.href,'','');return false"
    ** This is code salad:
    href="”PR_Launch.pdf”" link="" will="" open="" a=""
    .pdf=""
    file.”="">More (PR_Launch.pdf,
    230kb)</a></span></td>
    Change it to:
    href="pdf/PR_Launch.pdf">More (PR_Launch.pdf,
    230kb)</a></td>
    If you continue to have trouble, you might find my divaPOP
    Extension
    easier, and far more powerful. It automat6ically opens pdf
    files and
    links to all external files in a popup window without your
    needing to
    code each link:
    http://www.divahtml.com/products/divaPOP/open_popup_windows.php
    E. Michael Brandt
    www.divaHTML.com
    divaPOP : standards-compliant popup windows
    divaGPS : you-are-here menu highlighting
    divaFAQ : FAQ pages with pizazz
    www.valleywebdesigns.com/vwd_Vdw.asp
    JustSo PictureWindow
    JustSo PhotoAlbum, et alia

  • Not able to open links to open pdf files, nothing happens, no error messages.

    work site requires pdf files to be downloaded, after updating FireFox I can't do this any longer. I have added site to "exception" for pop-ups, still nothing.

    There needs to be an entry for the XI/ PI server....unless you make an entry you wont be able to access the links....can you try accessing the following link:
    http://<IP-Address of PI>:<JAVA PORT of PI>/rwb/FrontComponent/FC_Secure.jsp?doAction=showMessageMonitoring
    pi.com is not a standard....it was just an example.....thats why i mentioned get the FQDN from your team members
    regards,
    Abhishek.
    Edited by: abhishek salvi on Mar 22, 2010 1:22 PM

  • How can I use links to open music files (aiff)?

    I want to create a pdf file with links to a large number of music files (too many to embed in the pdf). When I create a link in the normal way Adobe Reader gives me a message that it cannot open the files. How can I get round this?

    I am using the link tool to open a file. The error message -

  • Open .doc file in java on Windows 98/2000

    Hi all,
    I need to open a .doc file on Windows 98/2000 PC thriugh java.I have used the command
    Runtime.getRuntime().exec(new String[] {"cmd", "/C", "start", "\"\"", filename});
    This command works fine on Window 2000 but gives IO Exception: CreateProcess: start <filename> error=2
    So I tried the command
    Runtime.getRuntime().exec("start"+filename);
    Now this command works fine on Windows 98 but gives the same error on Win2000.
    Someone please suggest a command which will work fine on all Windows OS.
    Thanks in advance

    Have a look at the Java Desktop Integration Components Project https://jdic.dev.java.net/documentation/index.html
    especially look at
    https://jdic.dev.java.net/nonav/documentation/javadoc/jdic/org/jdesktop/jdic/desktop/Desktop.html#open(java.io.File)
    which opens a File using the default application associated with this kind of file.

  • How to Open a file by JAVA SCRIPT in ABAP?

    Hi Experts,
    i'm trying to open a pdf file in java script (ONLY) through ABAP.
    Is it possible? If so how?
    The java script what we write in HTML is "window.open("C:
    Temp
    file.pdf");"
    Please advice ASAP.
    Somnath

    Hi,
    You have to make the Vi reentrant so that it does not share the same memory location:
    Regards,
    Even
    Certified LabVIEW Associate Developer
    Automated Test Developer
    Topro AS
    Norway

  • Opening a  File in Java

    The name of Ms-Exel file is stored in Ms-Access Database.
    Ms-Access Database . Report.dat
    There two Columns
    Rep_Name = which will have the Report Name
    Rep_Excel = Which will have Excel File name
    i will be creating a GUI whereby I will access the database and display the report names.
    Depending on what the user selects I woukd l like to make a call to Excel and Open that respected file for that Rep_Name.
    The File I am opening in Excel will be taken from the MS-ACCESS DATABASE.
    After the report is displayed , on clicking the close button there should be option to come back to the java program

    1. retieve th efilename from th edatabase.
    2. open the excel file
    for #2, if you want tyo open it within your Java application (so your Java application have access to the file..like to modify and update the Excel file)..then you will ned some sort of Excel API, like Jakarta POI as suggested. If you just want to open the excel file using MS Excel application (your Java application will not be able to do anything - like modify the Open Excel file) , then you can use Runtime class and its exec() method to launch the Excel application.

  • Opening .doc files from Java

    Ok, here's my problem.
    I'm using Java to create an autorun program for a little thing I'm putting together.
    One of the options should be "Read documentation" . However, to do that, I need to make my program open a Microsoft Word (.doc) document. What is the command/how can I do this? By open, I mean open the file in MS Word for viewing.

    When you say "where filename is the path" do you mean
    type in "\documentation\file.doc" or is it a variable?It's a variable in the example. It doesn't matter -- just as long as the resulting string passed to exec will contain the correct file name so the OS will see it.

  • Opening image files in java applet

    Hi,
    I made an applet that opens up the image file and displays it.
    When the photo is loaded, the program sets boolean photoLoaded = true;
    and when the image is loaded, it has to do something else.
    the problem is that I have to open the file twice meaning I would click
    "open" button and select the photo, which doesn't do anything, so I have to go back
    and click open button, select the photo, and open up again.
    When I changed the code slightly so that it shows the first time, photoLoaded is still false the first time,
    so I still have to open it up twice for photoLoaded to be true.
    methods for opening an image file:
        private void loadPhoto() throws Exception{
            Frame parent = new Frame();
            FileDialog fd = new FileDialog(parent, "Please choose a image file:",
                FileDialog.LOAD);
            fd.show();
            String selectedImage = fd.getFile();
            if(selectedImage == null){
                // no image file selected
            }else{
                File ffile = new File(fd.getDirectory() + File.separator +
                                    fd.getFile());
                boolean canOpen = accept(ffile);
                if(canOpen){
                    imageLoaded = kit.getImage(selectedImage);
                    width = imageLoaded.getWidth(ob);
                    height = imageLoaded.getHeight(ob);
                    /*get image*/
                    imageLoaded = getImage(getCodeBase(), selectedImage);
                    tracker.addImage(imageLoaded, 0);
                    /* wait until image is loaded */
                    try{
                        tracker.waitForAll();
                        photoLoaded = true;
                    }catch(InterruptedException ex) {
                        //does nothing
                    repaint();
        public boolean accept(File f){
            if(f.isDirectory()){
                return true;
            String extension = Utils.getExtension(f);
            if(extension !=null){
                if(extension.equals(Utils.gif) ||
                   extension.equals(Utils.jpeg) ||
                   extension.equals(Utils.jpg)){
                       return true;
                } else{
                    return false;
            return false;
        public static class Utils{
            public final static String jpeg = "jpeg";
            public final static String jpg = "jpg";
            public final static String gif = "gif";
            /* get the extension of a file */
            public static String getExtension(File f){
                String ext = null;
                String s = f.getName();
                int i = s.lastIndexOf('.');
                if(i>0 && i<s.length()-1){
                    ext = s.substring(i+1).toLowerCase();
                return ext;
        }and the paint method:
        public void paint(Graphics g)
            g.drawImage(background, 0, 0, this);
            if(photoLoaded == true){
                g.drawImage(imageLoaded, startingPtX, startingPtY, ob);
        }does anybody have idea on what's wrong with it?
    thanks!

    Is this what you mean by you have to load it twice? You load the image, then add it to the MediaTracker, then you do what ever you want with it--like get the width and height and set you flags.
       imageLoaded = kit.getImage(selectedImage);
       width = imageLoaded.getWidth(ob);
       height = imageLoaded.getHeight(ob);
       /*get image*/
       imageLoaded = getImage(getCodeBase(), selectedImage);
       tracker.addImage(imageLoaded, 0);

  • How can we open any file using JAVA...

    Hi all
    i trying to make code in that code i choose a file using a filechooser then put that file name in FILE object like (File file = fileChooser.getSelectedFile();)
    but the thing is how can i open that file for example if that file is HTML file then opens in IE or if that file is MS Word document that open in Word, like that
    is there any suggestions
    Thanx
    Regards
    Satinderjit

    start is a windows command-line utility.
    start foo.doc will start Word (or Star Office or Word Perfect or whatever is registered for the .doc extension),
    start bar.htmnl will start your registered browser etc.

  • WAD - Link to open PDF file

    Hello,
    I created an application in WAD - some tables, some buttons etc. I need to add a link (or button, not the matter), where user can click to open attached PDF file. PDF can be stored anywhere (i.e. in "Documents" in RSA1 or as a regular file on the server). Any idea? When I use the "Document" web item, it opens a parameters window, not the document itself. I need to open just a document.
    Arelis

    Hi Arelis,
    either you can use a hyperlink as described by Andrey or a button. There is a quite good post which describes how to open a document by using a java script coding behind a regular web template button:
    Help button in WAD 7.X
    Brgds,
    Marcel

  • Opening HTML file from java GUI

    Can someone please tell me how I can open a HTML file in Internet Explorer from a Java GUI,
    I have an asssignment I am doing for college and I was toying with the idea of putting in helpfiles, for the program, can anyone tell me the easiest way of apcomplishing this???
    Thanks in advance for your help,
    Kaspah

    Although this should answer your question, there are other (cross platform) ways to do what you want. As opposed to your "must have internet explorer" solution. Swing has a built in html viewer you might use, for example. I've been doing some reading on java/xml solutions. I don't consider myself knowledgeable enough (yet) to comment on that solution though. A delimited text file would be another solution. Useing that solution you could treat the file like a set of parrallel arrays on the hard drive and disply your text on pre-formated labels. Anyway, here is a link to you answer......
    http://java.sun.com/products/jdk/1.2/docs/api/java/lang/Runtime.html#exec(java.lang.String)
    Ron_W

Maybe you are looking for