我的项目结构如下:

/src/main/java/
/src/main/resources/
/src/test/java/
/src/test/resources/

我在/src/test/resources/test.csv中有一个文件,我想从/src/test/java/MyTest.java中的单元测试中加载该文件

我有个不能用的代码。它会提示“没有这样的文件或目录”。

BufferedReader br = new BufferedReader (new FileReader(test.csv))

我也试过这个

InputStream is = (InputStream) MyTest.class.getResourcesAsStream(test.csv))

这也行不通。它返回null。我正在使用Maven构建我的项目。


当前回答

导入以下文件:

import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.ArrayList;

下面的方法返回一个字符串数组列表中的文件:

public ArrayList<String> loadFile(String filename){

  ArrayList<String> lines = new ArrayList<String>();

  try{

    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream inputStream = classloader.getResourceAsStream(filename);
    InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
    BufferedReader reader = new BufferedReader(streamReader);
    for (String line; (line = reader.readLine()) != null;) {
      lines.add(line);
    }

  }catch(FileNotFoundException fnfe){
    // process errors
  }catch(IOException ioe){
    // process errors
  }
  return lines;
}

其他回答

getResource()只能在src/main/resources中使用资源文件。要获取src/main/resources路径之外的文件,比如src/test/java,你需要明确地创建它。

下面的例子可能会帮助你

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

public class Main {
    public static void main(String[] args) throws URISyntaxException, IOException {
        URL location = Main.class.getProtectionDomain().getCodeSource().getLocation();
        BufferedReader br = new BufferedReader(new FileReader(location.getPath().toString().replace("/target/classes/", "/src/test/java/youfilename.txt")));
    }
}

Try:

InputStream is = MyTest.class.getResourceAsStream("/test.csv");

IIRC getResourceAsStream()默认是相对于类的包。

正如@Terran所指出的,不要忘记在文件名的开头添加/

您可以使用com.google.common.io.Resources.getResource读取文件的url,然后使用java.nio.file.Files获取文件内容来读取文件的内容。

URL urlPath = Resources.getResource("src/main/resource");
List<String> multilineContent= Files.readAllLines(Paths.get(urlPath.toURI()));

我在测试文件夹中找不到我的文件,即使我按照答案。重建项目解决了这个问题。IntelliJ似乎没有自动识别新文件。发现这个很让人不快。

现在我正在说明从maven创建的资源目录中读取字体的源代码,

可控硅/主/资源/ calibril.ttf

Font getCalibriLightFont(int fontSize){
    Font font = null;
    try{
        URL fontURL = OneMethod.class.getResource("/calibril.ttf");
        InputStream fontStream = fontURL.openStream();
        font = new Font(Font.createFont(Font.TRUETYPE_FONT, fontStream).getFamily(), Font.PLAIN, fontSize);
        fontStream.close();
    }catch(IOException | FontFormatException ief){
        font = new Font("Arial", Font.PLAIN, fontSize);
        ief.printStackTrace();
    }   
    return font;
}

它为我工作,希望整个源代码也将帮助你,享受!