有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在maven项目中从主包访问测试资源

作为练习的一部分,我正在开发代码,该代码将读取一个文件并检查它是否有浮动。我已经编写了代码,但我不确定是否正确访问了文件,或者是否有更好的方法

应用程序:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Question1 {
    /* Write a method public ArrayList<Double> readValues(String filename) throws ... that reads a file
     * containing floating-point numbers. Throw appropriate exceptions if the file could not be opened
     * or if some of the inputs are not floating-point numbers.
     */

    private static final String RESOURCE_BASE_PATH = "src/test/resources/";

    //under src/main/ java : java_impatient.chapter4.Question1
    public static List<Double> readValues(String filename) throws IOException {
        ArrayList<Double> values = new ArrayList<>();
        try (BufferedReader fileReader = new BufferedReader(new FileReader(filename))) {
            //TODO : Complete this with TDD ?
        }
        return values;
    }

}

测试:

import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.io.*;

import java.util.List;

public class Question1Test {
    //Some other test code here.

    //under src/test : testjava_impatient.chapter4.Question1Test
    @Test
    public void returnsEmptyListForEmptyFile() throws Exception {
        //Is this the best way to get the full path of a file?
        List<Double> values = Question1.readValues( getFilePath("src/test/resources/chapter4/question1_empty.txt") );
        Assert.assertTrue(values.isEmpty(), "List is not empty as expected!");
    }

    private static String getFilePath(String relativePath){
       File file = new File(RESOURCE_BASE_PATH + relativePath);
       String fullPath = file.getAbsolutePath();
       return fullPath;
    }

}

共 (1) 个答案

  1. # 1 楼答案

    Maven默认情况下将“.java”文件打包为“src/*/java”中的“.class”和“src/*/resources”中的“*”文件,您不会使用“src/*/*”,因为编译后它不存在

    只需使用java和resources文件夹中的文件夹结构

    另外,不要忘记,您想要访问的文件可能在运行的jar中,或者在ide生成的构建结构中

    如果您没有更改资源的打包方式,要访问资源,您可以使用:

    Class<T> {
        public InputStream getResourceAsStream(String name);
        public URL getResource(String name);
    }
    

    您可以使用相对路径或绝对路径(在resources文件夹中)

    例如:

    1. 相对的“question1_empty.txt”(如果两个元素都在“第4章”中)
    2. 绝对“第4章/问题1_empty.txt”

    使用InputStreamReader代替FileReader

    new InputStreamReader(Question1Test.class.getResourceAsStream("question1_empty.txt"));
    new InputStreamReader(Question1Test.class.getResource("question1_empty.txt").openStream());