Snowflake
Snowflake

Reputation: 3081

How to open the temporary directory in Java?

Dear community members,

I have a small problem with the following code. I think it should open the explorer in the C:\Users\Me\AppData\Local\Temp\ directory. However that does not work, actually nothing happens. No errors.

I have used the following code:

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try {
            Desktop.getDesktop().open(File.createTempFile("abcd", ".temp").getParentFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

If I replace it with a normal file, like new File("C:\"), then it does work. Can someone explain to me why it does not work?

PS: guys I forgot to tell you I also tried it with some characters like "abcd", it still gives nothing and shows nothing!

Upvotes: 1

Views: 5930

Answers (3)

Vincent
Vincent

Reputation: 1035

Just use new File(System.getProperty("java.io.tmpdir")): that's the temp directory. No need for dirty tricks with the parent of a useless temporary file...

Upvotes: 5

Michał Kosmulski
Michał Kosmulski

Reputation: 10020

According to the docs for File.createTempFile(), if the prefix (first argument) contains fewer than three characters, an IllegalArgumentException will be thrown. You should see it in your console output.

Upvotes: 0

ulmangt
ulmangt

Reputation: 5423

Looking at the Javadoc for the File class:

Parameters:

prefix - The prefix string to be used in generating the file's name; must be at least three characters long

So it appears that "" isn't a valid argument for the file prefix.

Upvotes: 0

Related Questions