Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从资源文件夹加载文件?_Java_File_Maven - Fatal编程技术网

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

Java 如何从资源文件夹加载文件?,java,file,maven,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中的单元测试加载该文件 我有一个不起作用的代码。它抱怨“没有这样的文件或目录” 我也试过这个 InputStream is = (InputStream) MyTest.class.getRes

我的项目具有以下结构:

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

我有一个不起作用的代码。它抱怨“没有这样的文件或目录”

我也试过这个

InputStream is = (InputStream) MyTest.class.getResourcesAsStream(test.csv))
这也不行。它返回
null
。我正在使用Maven构建我的项目。

尝试:

InputStream is = MyTest.class.getResourceAsStream("/test.csv");
默认情况下,IIRC
getResourceAsStream()
是相对于类的包的

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

尝试下一步:

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

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

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

src\main\java\com\company\test\YourCallingClass.java src\main\java\com\opensymphony\xwork2\util\ClassLoaderUtil.java src\main\resources\test.csv
注释

  • 在回程机器中
  • 也在

  • 当不运行Maven构建jar时,例如从IDE运行时,代码是否工作?如果是这样,请确保该文件实际包含在jar中。资源文件夹应包含在pom文件中的


    如果使用上下文类加载器查找资源,那么肯定会降低应用程序的性能

    以下类可用于从
    类路径
    加载
    资源
    ,并在给定的
    文件路径
    出现问题时接收拟合错误消息

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

    下面是一个使用以下工具的快速解决方案:

    用法:

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

    我让它在没有任何“类”或“类加载器”的情况下工作

    假设我们有三个场景,其中文件“example.file”的位置和您的工作目录(应用程序执行的位置)是home/mydocuments/program/projects/myapp:

    a) 工作目录的子文件夹子目录: myapp/res/files/example.file

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

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

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

    1) 找到正确的路径: a)
    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”

    基本上,如果它是根文件夹,则路径名以斜杠开头。 如果它是子文件夹,则路径名前不得有斜杠。如果子文件夹不是工作目录的子文件夹,则必须使用“./”将其cd到。这告诉系统向上移动一个文件夹

    2) 通过传递正确的路径创建文件对象:

    File file = new File(path);
    
    3) 您现在可以开始了:

    BufferedReader br = new BufferedReader(new FileReader(file));
    
    getResource()可以很好地处理仅放置在
    src/main/resources
    中的资源文件。要获取路径不是
    src/main/resources
    say
    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")));
        }
    }
    

    尝试在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);
    
    还是非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);
    

    现在我演示了从maven创建的资源目录中读取字体的源代码

    scr/main/resources/calibril.ttf

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

    导入以下内容:

    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;
    }
    
    publicArrayList加载文件(字符串文件名){
    ArrayList行=新的ArrayList();
    试一试{
    ClassLoader ClassLoader=Thread.currentThread().getContextClassLoader();
    InputStream InputStream=classloader.getResourceAsStream(文件名);
    InputStreamReader streamReader=新的InputStreamReader(inputStream,StandardCharsets.UTF_8);
    BufferedReader reader=新的BufferedReader(streamReader);
    for(字符串行;(line=reader.readLine())!=null;){
    行。添加(行);
    }
    }捕获(FileNotFoundException fnfe){
    //过程错误
    }捕获(ioe异常ioe){
    //过程错误
    }
    回流线;
    }
    
    我通过编写

    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);
    
    我面对着

    类加载器没有找到该文件,这意味着它没有打包到工件(jar)中。您需要构建项目。例如,对于maven:

    mvn clean install
    
    因此,添加到resources文件夹中的文件将进入maven build并可供应用程序使用


    我想保留我的答案:它不解释如何读取文件(其他答案确实解释了这一点),它回答为什么
    输入流
    资源
    。类似。

    对于1.7之后的java

     List<String> lines = Files.readAllLines(Paths.get(getClass().getResource("test.csv").toURI()));
    
    List lines=Files.readAllLines(path.get(getClass().getResource(“test.csv”).toURI());
    
    非spring项目:

    String filePath = Objects.requireNonNull(getClass().getClassLoader().getResource("any.json")).getPath();
    
    Stream<String> lines = Files.lines(Paths.get(filePath));
    
    对于spring项目,还可以使用一行代码获取resources文件夹下的任何文件:

    File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "any.json");
    
    String content = new String(Files.readAllBytes(file.toPath()));
    

    您可以使用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()));
    
    URL urlPath=Resources.getResource(“src/main/resource”);
    List multilecontent=Files.readAllLines(path.get(urlPath.toURI());
    
    如果以静态方法加载文件,则
    ClassLoader ClassLoader=getClass().getClassLoader()
    这可能会给你一个错误

    你可以试试这个 e、 g.要从资源中加载的文件是resources>>Images>>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();
    

    即使我按照答案操作,也无法在测试文件夹中找到我的文件。通过重建项目解决了这个问题。IntelliJ似乎没有自动识别新文件。很难找到答案。

    要从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());
    
    不起作用怎么办?
    String filePath = Objects.requireNonNull(getClass().getClassLoader().getResource("any.json")).getPath();
    
    InputStream in = new FileInputStream(filePath);
    
    File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "any.json");
    
    String content = new String(Files.readAllBytes(file.toPath()));
    
    URL urlPath = Resources.getResource("src/main/resource");
    List<String> multilineContent= Files.readAllLines(Paths.get(urlPath.toURI()));
    
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.Resource;
    
    Resource resource = new ClassPathResource("Images/Test.gif");
    
        File file = resource.getFile();
    
    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());