Maven exec:java : how to open and read a file in the resources directory?How to create a file in src/main/resourcesHow do I read / convert an InputStream into a String in Java?How can I create an executable JAR with dependencies using Maven?Maven: how to get a war package with resources copied in WEB-INF?How to add local jar files to a Maven project?IntelliJ inspection gives “Cannot resolve symbol” but still compiles codeMaven does not find JUnit tests to runreading from a file with Mavenmaven-archetype-webapp directory structure using Eclipse KeplerNot able to read resource file in maven jarMaven war source directory

TGV timetables / schedules?

How old can references or sources in a thesis be?

Why do I get two different answers for this counting problem?

How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?

Fencing style for blades that can attack from a distance

How to write a macro that is braces sensitive?

Mathematical cryptic clues

How do I create uniquely male characters?

What does "Puller Prush Person" mean?

To string or not to string

Prove that NP is closed under karp reduction?

Is it tax fraud for an individual to declare non-taxable revenue as taxable income? (US tax laws)

Is it unprofessional to ask if a job posting on GlassDoor is real?

Why dont electromagnetic waves interact with each other?

Today is the Center

Can a Warlock become Neutral Good?

Why are electrically insulating heatsinks so rare? Is it just cost?

Why not use SQL instead of GraphQL?

How can I prevent hyper evolved versions of regular creatures from wiping out their cousins?

Why don't electron-positron collisions release infinite energy?

How does one intimidate enemies without having the capacity for violence?

What are these boxed doors outside store fronts in New York?

Minkowski space

Have astronauts in space suits ever taken selfies? If so, how?



Maven exec:java : how to open and read a file in the resources directory?


How to create a file in src/main/resourcesHow do I read / convert an InputStream into a String in Java?How can I create an executable JAR with dependencies using Maven?Maven: how to get a war package with resources copied in WEB-INF?How to add local jar files to a Maven project?IntelliJ inspection gives “Cannot resolve symbol” but still compiles codeMaven does not find JUnit tests to runreading from a file with Mavenmaven-archetype-webapp directory structure using Eclipse KeplerNot able to read resource file in maven jarMaven war source directory






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








18















here is the structure of my project.



proj
---src
----main
----java
----Main.java
----resources
----res.txt


I am using m2eclipse plugin with Eclipse.
In Main.java, I have



File f = new File("res.txt"); System.out.println(f.getAbsolutePath());


When I run mvn exec:java, the path got printed out is "...projres.txt". How can I make it look for the resource file in "...projtargetclasses" directory?



EDIT:



Thanks for the answers to my original question. I have a follow-up questions:



So basically what I want to do is to have the Main class read the "res.txt" and then generate a new "newres.txt" to the resources directory so that I can package this new "newres.txt" to the jar file in the package phase later. Currently I mounted this exec:java to the prepare-package phase. How should I create this "newres.txt" in the resources directory without a hard-coded absolute path or depending on the directory structure of Maven?










share|improve this question






























    18















    here is the structure of my project.



    proj
    ---src
    ----main
    ----java
    ----Main.java
    ----resources
    ----res.txt


    I am using m2eclipse plugin with Eclipse.
    In Main.java, I have



    File f = new File("res.txt"); System.out.println(f.getAbsolutePath());


    When I run mvn exec:java, the path got printed out is "...projres.txt". How can I make it look for the resource file in "...projtargetclasses" directory?



    EDIT:



    Thanks for the answers to my original question. I have a follow-up questions:



    So basically what I want to do is to have the Main class read the "res.txt" and then generate a new "newres.txt" to the resources directory so that I can package this new "newres.txt" to the jar file in the package phase later. Currently I mounted this exec:java to the prepare-package phase. How should I create this "newres.txt" in the resources directory without a hard-coded absolute path or depending on the directory structure of Maven?










    share|improve this question


























      18












      18








      18


      3






      here is the structure of my project.



      proj
      ---src
      ----main
      ----java
      ----Main.java
      ----resources
      ----res.txt


      I am using m2eclipse plugin with Eclipse.
      In Main.java, I have



      File f = new File("res.txt"); System.out.println(f.getAbsolutePath());


      When I run mvn exec:java, the path got printed out is "...projres.txt". How can I make it look for the resource file in "...projtargetclasses" directory?



      EDIT:



      Thanks for the answers to my original question. I have a follow-up questions:



      So basically what I want to do is to have the Main class read the "res.txt" and then generate a new "newres.txt" to the resources directory so that I can package this new "newres.txt" to the jar file in the package phase later. Currently I mounted this exec:java to the prepare-package phase. How should I create this "newres.txt" in the resources directory without a hard-coded absolute path or depending on the directory structure of Maven?










      share|improve this question
















      here is the structure of my project.



      proj
      ---src
      ----main
      ----java
      ----Main.java
      ----resources
      ----res.txt


      I am using m2eclipse plugin with Eclipse.
      In Main.java, I have



      File f = new File("res.txt"); System.out.println(f.getAbsolutePath());


      When I run mvn exec:java, the path got printed out is "...projres.txt". How can I make it look for the resource file in "...projtargetclasses" directory?



      EDIT:



      Thanks for the answers to my original question. I have a follow-up questions:



      So basically what I want to do is to have the Main class read the "res.txt" and then generate a new "newres.txt" to the resources directory so that I can package this new "newres.txt" to the jar file in the package phase later. Currently I mounted this exec:java to the prepare-package phase. How should I create this "newres.txt" in the resources directory without a hard-coded absolute path or depending on the directory structure of Maven?







      java maven






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 17 '11 at 18:06







      wei

















      asked May 16 '11 at 22:59









      weiwei

      2,60662943




      2,60662943






















          5 Answers
          5






          active

          oldest

          votes


















          20














          I guess I will answer my own question, Thread.currentThread().getContextClassLoader().getResourceAsStream()
          works the best for me, especially when the project produces a jar dependency for another web project.






          share|improve this answer























          • You are the best! THANK YOU

            – Angelo
            Dec 10 '15 at 14:34


















          14














          Figure I'd add to the answers.



          You can also use:



          InputStream file = ClassLoader.getSystemResourceAsStream("res.txt");





          share|improve this answer


















          • 1





            This solved my problem for me! Thank you so much for taking the time to write this solution up!!!

            – Wulf
            Aug 27 '13 at 21:27











          • glad it helped!

            – Cuga
            Aug 28 '13 at 15:28


















          12














          Try



          InputStream IS = Main.class.getResourceAsStream("res.txt");


          to access the content of res.txt. Pay attention to the encoding of your text file (beware of defaults). If your maven project is set on UTF-8 for example, make sure res.txt is encoded in UTF-8 too, otherwise, you'll get funny errors at runtime.






          share|improve this answer

























          • More on this in a blog post I created recently: tshikatshikaaa.blogspot.nl/2012/07/…

            – Jérôme Verstrynge
            Jul 27 '12 at 13:26











          • See javaworld.com/javaqa/2003-08/01-qa-0808-property.html?page=2 about when to use a leading '/' for the resource path.

            – leo
            Jul 8 '13 at 14:29


















          1














          When run from eclipse, res.txt is created in/reader from the folder where eclipse is started. Hence the output.



          If you want to make the code look at the file in a specific folder, which is present in your classpath, then you should try using getResourceAsStream() method.



          Alternately you can specify the absolute path of the file.






          share|improve this answer






























            0














            Here is anther solution:



            String str = "target/classes/res.txt";

            InputStream is = new FileInputStream(new File(str));


            If you exec java in root folder, and you resource will compile to target/classes folder, you can write you code like this.






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6024353%2fmaven-execjava-how-to-open-and-read-a-file-in-the-resources-directory%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              5 Answers
              5






              active

              oldest

              votes








              5 Answers
              5






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              20














              I guess I will answer my own question, Thread.currentThread().getContextClassLoader().getResourceAsStream()
              works the best for me, especially when the project produces a jar dependency for another web project.






              share|improve this answer























              • You are the best! THANK YOU

                – Angelo
                Dec 10 '15 at 14:34















              20














              I guess I will answer my own question, Thread.currentThread().getContextClassLoader().getResourceAsStream()
              works the best for me, especially when the project produces a jar dependency for another web project.






              share|improve this answer























              • You are the best! THANK YOU

                – Angelo
                Dec 10 '15 at 14:34













              20












              20








              20







              I guess I will answer my own question, Thread.currentThread().getContextClassLoader().getResourceAsStream()
              works the best for me, especially when the project produces a jar dependency for another web project.






              share|improve this answer













              I guess I will answer my own question, Thread.currentThread().getContextClassLoader().getResourceAsStream()
              works the best for me, especially when the project produces a jar dependency for another web project.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered May 29 '11 at 20:04









              weiwei

              2,60662943




              2,60662943












              • You are the best! THANK YOU

                – Angelo
                Dec 10 '15 at 14:34

















              • You are the best! THANK YOU

                – Angelo
                Dec 10 '15 at 14:34
















              You are the best! THANK YOU

              – Angelo
              Dec 10 '15 at 14:34





              You are the best! THANK YOU

              – Angelo
              Dec 10 '15 at 14:34













              14














              Figure I'd add to the answers.



              You can also use:



              InputStream file = ClassLoader.getSystemResourceAsStream("res.txt");





              share|improve this answer


















              • 1





                This solved my problem for me! Thank you so much for taking the time to write this solution up!!!

                – Wulf
                Aug 27 '13 at 21:27











              • glad it helped!

                – Cuga
                Aug 28 '13 at 15:28















              14














              Figure I'd add to the answers.



              You can also use:



              InputStream file = ClassLoader.getSystemResourceAsStream("res.txt");





              share|improve this answer


















              • 1





                This solved my problem for me! Thank you so much for taking the time to write this solution up!!!

                – Wulf
                Aug 27 '13 at 21:27











              • glad it helped!

                – Cuga
                Aug 28 '13 at 15:28













              14












              14








              14







              Figure I'd add to the answers.



              You can also use:



              InputStream file = ClassLoader.getSystemResourceAsStream("res.txt");





              share|improve this answer













              Figure I'd add to the answers.



              You can also use:



              InputStream file = ClassLoader.getSystemResourceAsStream("res.txt");






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Aug 9 '12 at 18:36









              CugaCuga

              10.7k2892143




              10.7k2892143







              • 1





                This solved my problem for me! Thank you so much for taking the time to write this solution up!!!

                – Wulf
                Aug 27 '13 at 21:27











              • glad it helped!

                – Cuga
                Aug 28 '13 at 15:28












              • 1





                This solved my problem for me! Thank you so much for taking the time to write this solution up!!!

                – Wulf
                Aug 27 '13 at 21:27











              • glad it helped!

                – Cuga
                Aug 28 '13 at 15:28







              1




              1





              This solved my problem for me! Thank you so much for taking the time to write this solution up!!!

              – Wulf
              Aug 27 '13 at 21:27





              This solved my problem for me! Thank you so much for taking the time to write this solution up!!!

              – Wulf
              Aug 27 '13 at 21:27













              glad it helped!

              – Cuga
              Aug 28 '13 at 15:28





              glad it helped!

              – Cuga
              Aug 28 '13 at 15:28











              12














              Try



              InputStream IS = Main.class.getResourceAsStream("res.txt");


              to access the content of res.txt. Pay attention to the encoding of your text file (beware of defaults). If your maven project is set on UTF-8 for example, make sure res.txt is encoded in UTF-8 too, otherwise, you'll get funny errors at runtime.






              share|improve this answer

























              • More on this in a blog post I created recently: tshikatshikaaa.blogspot.nl/2012/07/…

                – Jérôme Verstrynge
                Jul 27 '12 at 13:26











              • See javaworld.com/javaqa/2003-08/01-qa-0808-property.html?page=2 about when to use a leading '/' for the resource path.

                – leo
                Jul 8 '13 at 14:29















              12














              Try



              InputStream IS = Main.class.getResourceAsStream("res.txt");


              to access the content of res.txt. Pay attention to the encoding of your text file (beware of defaults). If your maven project is set on UTF-8 for example, make sure res.txt is encoded in UTF-8 too, otherwise, you'll get funny errors at runtime.






              share|improve this answer

























              • More on this in a blog post I created recently: tshikatshikaaa.blogspot.nl/2012/07/…

                – Jérôme Verstrynge
                Jul 27 '12 at 13:26











              • See javaworld.com/javaqa/2003-08/01-qa-0808-property.html?page=2 about when to use a leading '/' for the resource path.

                – leo
                Jul 8 '13 at 14:29













              12












              12








              12







              Try



              InputStream IS = Main.class.getResourceAsStream("res.txt");


              to access the content of res.txt. Pay attention to the encoding of your text file (beware of defaults). If your maven project is set on UTF-8 for example, make sure res.txt is encoded in UTF-8 too, otherwise, you'll get funny errors at runtime.






              share|improve this answer















              Try



              InputStream IS = Main.class.getResourceAsStream("res.txt");


              to access the content of res.txt. Pay attention to the encoding of your text file (beware of defaults). If your maven project is set on UTF-8 for example, make sure res.txt is encoded in UTF-8 too, otherwise, you'll get funny errors at runtime.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Aug 2 '12 at 19:33

























              answered May 17 '11 at 3:09









              Jérôme VerstryngeJérôme Verstrynge

              28.9k66224392




              28.9k66224392












              • More on this in a blog post I created recently: tshikatshikaaa.blogspot.nl/2012/07/…

                – Jérôme Verstrynge
                Jul 27 '12 at 13:26











              • See javaworld.com/javaqa/2003-08/01-qa-0808-property.html?page=2 about when to use a leading '/' for the resource path.

                – leo
                Jul 8 '13 at 14:29

















              • More on this in a blog post I created recently: tshikatshikaaa.blogspot.nl/2012/07/…

                – Jérôme Verstrynge
                Jul 27 '12 at 13:26











              • See javaworld.com/javaqa/2003-08/01-qa-0808-property.html?page=2 about when to use a leading '/' for the resource path.

                – leo
                Jul 8 '13 at 14:29
















              More on this in a blog post I created recently: tshikatshikaaa.blogspot.nl/2012/07/…

              – Jérôme Verstrynge
              Jul 27 '12 at 13:26





              More on this in a blog post I created recently: tshikatshikaaa.blogspot.nl/2012/07/…

              – Jérôme Verstrynge
              Jul 27 '12 at 13:26













              See javaworld.com/javaqa/2003-08/01-qa-0808-property.html?page=2 about when to use a leading '/' for the resource path.

              – leo
              Jul 8 '13 at 14:29





              See javaworld.com/javaqa/2003-08/01-qa-0808-property.html?page=2 about when to use a leading '/' for the resource path.

              – leo
              Jul 8 '13 at 14:29











              1














              When run from eclipse, res.txt is created in/reader from the folder where eclipse is started. Hence the output.



              If you want to make the code look at the file in a specific folder, which is present in your classpath, then you should try using getResourceAsStream() method.



              Alternately you can specify the absolute path of the file.






              share|improve this answer



























                1














                When run from eclipse, res.txt is created in/reader from the folder where eclipse is started. Hence the output.



                If you want to make the code look at the file in a specific folder, which is present in your classpath, then you should try using getResourceAsStream() method.



                Alternately you can specify the absolute path of the file.






                share|improve this answer

























                  1












                  1








                  1







                  When run from eclipse, res.txt is created in/reader from the folder where eclipse is started. Hence the output.



                  If you want to make the code look at the file in a specific folder, which is present in your classpath, then you should try using getResourceAsStream() method.



                  Alternately you can specify the absolute path of the file.






                  share|improve this answer













                  When run from eclipse, res.txt is created in/reader from the folder where eclipse is started. Hence the output.



                  If you want to make the code look at the file in a specific folder, which is present in your classpath, then you should try using getResourceAsStream() method.



                  Alternately you can specify the absolute path of the file.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered May 17 '11 at 2:48









                  RaghuramRaghuram

                  44.5k991110




                  44.5k991110





















                      0














                      Here is anther solution:



                      String str = "target/classes/res.txt";

                      InputStream is = new FileInputStream(new File(str));


                      If you exec java in root folder, and you resource will compile to target/classes folder, you can write you code like this.






                      share|improve this answer



























                        0














                        Here is anther solution:



                        String str = "target/classes/res.txt";

                        InputStream is = new FileInputStream(new File(str));


                        If you exec java in root folder, and you resource will compile to target/classes folder, you can write you code like this.






                        share|improve this answer

























                          0












                          0








                          0







                          Here is anther solution:



                          String str = "target/classes/res.txt";

                          InputStream is = new FileInputStream(new File(str));


                          If you exec java in root folder, and you resource will compile to target/classes folder, you can write you code like this.






                          share|improve this answer













                          Here is anther solution:



                          String str = "target/classes/res.txt";

                          InputStream is = new FileInputStream(new File(str));


                          If you exec java in root folder, and you resource will compile to target/classes folder, you can write you code like this.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 9 at 2:47









                          bitfishxyzbitfishxyz

                          5151417




                          5151417



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6024353%2fmaven-execjava-how-to-open-and-read-a-file-in-the-resources-directory%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                              2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                              Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme