如何从资源文件夹加载文件?

时间:2013-04-01 18:23:50

标签: java file maven

我的项目具有以下结构:

/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来构建我的项目。

22 个答案:

答案 0 :(得分:190)

尝试下一个:

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("test.csv");

如果上述方法不起作用,则会在以下类中添加各种项目:ClassLoaderUtil 1 (代码here)。 2

以下是如何使用该类的一些示例:

src\main\java\com\company\test\YourCallingClass.java
src\main\java\com\opensymphony\xwork2\util\ClassLoaderUtil.java
src\main\resources\test.csv
// java.net.URL
URL url = ClassLoaderUtil.getResource("test.csv", YourCallingClass.class);
Path path = Paths.get(url.toURI());
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// java.io.InputStream
InputStream inputStream = ClassLoaderUtil.getResourceAsStream("test.csv", YourCallingClass.class);
InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(streamReader);
for (String line; (line = reader.readLine()) != null;) {
    // Process line
}

备注

    The Wayback Machine 中的
  1. See it
  2. 同样在GitHub

答案 1 :(得分:48)

尝试:

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

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

答案 2 :(得分:32)

以下是使用Guava

的快速解决方案
import com.google.common.base.Charsets;
import com.google.common.io.Resources;

public String readResource(final String fileName, Charset charset) throws IOException {
        return Resources.toString(Resources.getResource(fileName), charset);
}

用法:

String fixture = this.readResource("filename.txt", Charsets.UTF_8)

答案 3 :(得分:21)

在Spring项目上尝试流动代码

ClassPathResource resource = new ClassPathResource("fileName");
InputStream inputStream = resource.getInputStream();

或非春季项目

 ClassLoader classLoader = getClass().getClassLoader();
 File file = new File(classLoader.getResource("fileName").getFile());
 InputStream inputStream = new FileInputStream(file);

答案 4 :(得分:5)

ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("test.csv");

如果使用上下文ClassLoader查找资源,那么肯定会降低应用程序性能。

答案 5 :(得分:5)

现在我将介绍从maven创建的资源目录中读取字体的源代码,

  

SCR /主/资源/ calibril.ttf

enter image description here

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;
}

它对我有用,并希望整个源代码也能帮到你,享受!

答案 6 :(得分:2)

对于Java 1.7之后的版本

Response Time Over Time Graph:

答案 7 :(得分:1)

导入以下内容:

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;
}

答案 8 :(得分:1)

您可以使用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()));

答案 9 :(得分:1)

对于spring项目,您还可以使用一行代码来获取资源文件夹下的任何文件:

File file = ResourceUtils.getFile("classpath:any.json");

String content = new String(Files.readAllBytes(file.toPath()));

答案 10 :(得分:0)

我通过将/scr/main/resources文件夹添加到我的Java Build Path来解决了这个问题

enter image description here

答案 11 :(得分:0)

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")));
    }
}

答案 12 :(得分:0)

我通过写成

在运行jar和IDE中都可以使用它

 InputStream schemaStream = ProductUtil.class.getClassLoader().getResourceAsStream(jsonSchemaPath);
            byte[] buffer = new byte[schemaStream.available()];
            schemaStream.read(buffer);

        File tempFile = File.createTempFile("com/package/schema/testSchema", "json");
        tempFile.deleteOnExit();
        FileOutputStream out = new FileOutputStream(tempFile);
        out.write(buffer);

答案 13 :(得分:0)

我遇到了同样的问题 Read file from /src/main/resources/

专家引起了问题 https://stackoverflow.com/a/55409569/4587961

mvn clean install

因此,添加到资源文件夹的文件将进入Maven构建并可供应用程序使用。

我想保留我的答案:它没有解释如何读取文件(其他答案确实说明了这一点),它回答为什么 InputStreamresource

答案 14 :(得分:0)

this.getClass().getClassLoader().getResource("filename").getPath()

答案 15 :(得分:0)

以下类可用于从resource加载classpath,并在给定filePath出现问题时收到错误消息。

import java.io.InputStream;
import java.nio.file.NoSuchFileException;

public class ResourceLoader
{
    private String filePath;

    public ResourceLoader(String filePath)
    {
        this.filePath = filePath;

        if(filePath.startsWith("/"))
        {
            throw new IllegalArgumentException("Relative paths may not have a leading slash!");
        }
    }

    public InputStream getResource() throws NoSuchFileException
    {
        ClassLoader classLoader = this.getClass().getClassLoader();

        InputStream inputStream = classLoader.getResourceAsStream(filePath);

        if(inputStream == null)
        {
            throw new NoSuchFileException("Resource file not found. Note that the current directory is the source folder!");
        }

        return inputStream;
    }
}

答案 16 :(得分:0)

不运行Maven-build jar时代码是否有效,例如从IDE运行时?如果是这样,请确保该文件实际包含在jar中。资源文件夹应包含在pom文件中,<build><resources>

答案 17 :(得分:0)

如果要以静态方法加载文件,则 ClassLoader classLoader = getClass().getClassLoader(); 这可能会给你一个错误。

您可以尝试一下 例如您要从资源加载的文件是资源>>图片>> Test.gif

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

Resource resource = new ClassPathResource("Images/Test.gif");

    File file = resource.getFile();

答案 18 :(得分:0)

即使我遵循了答案,也无法在测试文件夹中找到我的文件。通过重建项目解决了该问题。似乎IntelliJ无法自动识别新文件。真讨厌找出来。

答案 19 :(得分:0)

要从 src/resources 文件夹中读取文件,请尝试以下操作:

DataSource fds = new FileDataSource(getFileHandle("images/sample.jpeg"));

public static File getFileHandle(String fileName){
       return new File(YourClassName.class.getClassLoader().getResource(fileName).getFile());
}

在非静态引用的情况下:

return new File(getClass().getClassLoader().getResource(fileName).getFile());

答案 20 :(得分:-1)

在科特林,你可以做

fun getJsonFromRessources(jsonPath: String): String? {
    return Thread.currentThread().contextClassLoader
        .getResourceAsStream(jsonPath)
        .bufferedReader()
        .use { it.readText() }
}

答案 21 :(得分:-2)

我没有参考&#34; class&#34;或&#34; ClassLoader&#34;。

我们假设我们有三个方案,其中包含文件的位置&#39; example.file&#39;和您的工作目录(您的应用程序执行的位置)是home / mydocuments / program / projects / myapp:

a)工作目录的子文件夹后代: 的myapp / RES /文件/ example.file

b)子文件夹不是工作目录的后代: 项目/文件/ example.file

b2)另一个不属于工作目录的子文件夹: 程序/文件/ example.file

c)根文件夹: home / mydocuments / files / example.file(Linux;在Windows中替换home / with C:)

1)找到正确的道路: 一个)String path = "res/files/example.file"; B)String path = "../projects/files/example.file" B2)String path = "../../program/files/example.file" C)String path = "/home/mydocuments/files/example.file"

基本上,如果它是根文件夹,请使用前导斜杠启动路径名。 如果它是子文件夹,则路径名前不能包含斜杠。如果子文件夹不是工作目录的后代,则必须使用&#34; ../"来cd到它。这告诉系统上一个文件夹。

2)通过传递正确的路径创建一个File对象:

File file = new File(path);

3)你现在好了:

BufferedReader br = new BufferedReader(new FileReader(file));