简体   繁体   中英

File Path - Relative Path

I have a maven project and as part of my requirement , I need to read a file from within a Test class and thats in one of the directories inside the test folders.

My proj hierarchy is like this..

src
     --test
        ---java
             --org
                 --sample
                      --- MyTestClass.java
        ---jmeter
               ---load_data.csv

In MyTestClass.java I need to read the load_data.csv. My trials so far with File and Path have not yielded results

file.exists() is always giving me false...How can i find the file and read it

Regards

假设项目的根是src的父项,那么您的路径应为:

Paths.get("src", "test", "jmeter", "load_data.csv")

The question is 2 fold. How do you access a file from Maven, and second how do you access the file from your class. I am assuming your maven build is failing because it does not pass the test due to the missing file.

Quick and dirty ways:

Enter full path. Depending on OS navigate to the file in your terminal and type (OSX and nix): "pwd" and copy and paste the full path inside your new File() Windows: echo %cd% OR How to construct a relative path in Java from two absolute paths (or URLs)?

Better ways: You should probably add that file inside resources. By convention you want to place your resources inside that folder. It makes it easy to access inside your classes aka class.getResource("somefile.txt") no need to worry about relative path. Also it gets added to your jar when you are distributing your program. File Structure: Convention src-> main -> resources -> load_data.csv

In your case src -> test -> resources -> load_data.csv

Now how to reference a resource from maven. Hard way add resources during build below is from Maven documentation https://maven.apache.org/plugins/maven-resources-plugin .

<executions>
      <execution>
        <id>copy-resources</id>
        <!-- here the phase you need -->
        <phase>validate</phase>
        <goals>
          <goal>copy-resources</goal>
        </goals>
        <configuration>
          <outputDirectory>${basedir}/target/extra-resources</outputDirectory>
          <resources>          
            <resource>
              <directory>src/non-packaged-resources</directory>
              <filtering>true</filtering>
            </resource>
          </resources>              
        </configuration>            
      </execution>
    </executions>

If you don't want testResources to be part of the main distribution you need to add a test profile and exclude them from your main phase/build. Some more documentation https://maven.apache.org/plugins/maven-resources-plugin/testResources-mojo.html

src/test/resources/添加您的load_data.csv并进行相应查询

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM