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

                              Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                              Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                              How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page