0

So I have a java program that reads a file specified by using args

$ java Main somefile.txt

But how do I do it when I make it into a jar? Let's say that foo.jar contains

-META-INF
-Main.class
-someFile.txt

And run it with (without specifying args after)

java -jar foo.jar

How do I do that? Note that I also use gradle to assemble the jar.

ReconditusNeumen
  • 121
  • 1
  • 2
  • 12

1 Answers1

0

There are a couple approaches.

  • You can provide a Manifest file inside your jar file that tells the 'java' command what class to launch. This is called "setting the application entry point" in the Java tutorial. Then

    java -jar foo.jar src/sourceSets/resources/someFile.txt

  • You can also tell java to run your particular class from the jar file:

    java -cp foo.jar Main src/sourceSets/resources/someFile.txt

    From the comments and edit of the original question, it seems you want to run the java command without putting any arguments on that line, but also have the program receive arguments. There's not way to do that directly.

Instead, write your own little java program that invokes the original main() routine with the argument value you need:

public class MyAdapter {

    public static void main(String[] args) {
        OtherProgram.main(String[]{"somefile.txt});
    }

}

and then invoke that.

Somehow you have to get that "somefile.txt" string in there. if you can't provide it as an argument, you have to provide it in the jar file.

Bob Jacobsen
  • 1,150
  • 6
  • 9
  • Sorry I didn't make it clear enough, my problem is if I want to run the jar file without specifying args. Meaning, someFile.txt is inside foo.jar too. Sorry about the confusion. – ReconditusNeumen Jun 29 '18 at 06:31