Uni
Uni

Reputation: 13

How to locate and execute a file with java

I am making a game with java as kind of a side project and am still new to the language. I was wondering how I could run a file when i didn't know the complete path, like if I were to send the game to a friend, and he has a different path location than me. Thank you in advance for any help.

code I am currently using:

File file = new File("/Users/(my name)/Desktop/script1.vbs");
Desktop desktop = Desktop.getDesktop();
if(file.exists()) desktop.open(file);`

Upvotes: 1

Views: 499

Answers (3)

MaQuiNa1995
MaQuiNa1995

Reputation: 431

Or you can use this, to locate your file in the resources folder:

File file = new File("classpath:com/company/script1.vbs");

"classpath:Route Of Source folders/Name and extension of the file"

Upvotes: 0

Thomas Fritsch
Thomas Fritsch

Reputation: 10127

Instead of

File file = new File("/Users/(my name)/Desktop/script1.vbs");

you should better use

File file = new File(System.getProperty("user.home"), "Desktop/script1.vbs");

See also the list of System Properties

Upvotes: 0

vanillaSugar
vanillaSugar

Reputation: 551

You could place the file (script1.vbs) in the project folder, that way the path would always be like this...

File file = new File("script1.vbs")

Place the file, not in the src or bin folder, but in the root folder.

Upvotes: 1

Related Questions