1

Hi Im trying to open word file using java program. The program gives me the following error"

Cannot make a static reference to the non-static method open(File) from the type Desktop

I dont know how to fix this. Can you please help me. Thanks. Below is snippet of code.

@Override
public void actionPerformed(ActionEvent e) {
    List<File> files;
    File startingDirectory = new File("C:/Hello/");
    try {
        files = getFileListing(startingDirectory);
        for (File file : files){
            Desktop.open(file);
        }

    } catch (FileNotFoundException ex) {
        System.out.println("File Not Found");
}

2 Answers 2

1

Try

Desktop.getDesktop().open(file);

instead

You should also be making a check for Desktop.isDekstopSupported to make sure the functionality you are attempting to execute exists

Sign up to request clarification or add additional context in comments.

1 Comment

Nice to have an easy question for a change ;) Glad to be of assist
1

You need to instantiate a Desktop object first, like this:

Desktop d = Desktop.getDesktop();

After that you can invoke instance methods on the desktop object, like this:

d.open(file);

In your code, you were trying to invoke the instance method open() on the class Desktop, and that won't work. The only methods that can be invoked on a class are static methods, all the other methods need to be invoked on an instance of the corresponding class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.