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

发布于 2025-02-13 03:24:08 字数 535 浏览 0 评论 0 原文

我的项目具有以下结构:

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

My project has the following structure:

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

I have a file in /src/test/resources/test.csv and I want to load the file from a unit test in /src/test/java/MyTest.java

I have this code which didn't work. It complains "No such file or directory".

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

I also tried this

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

This also doesn't work. It returns null. I am using Maven to build my project.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(26

停滞 2025-02-20 03:24:08

尝试下一个:

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

如果以上不起作用,则添加了以下类别的各个项目: classLoaderutil 1 (代码在这里)。 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
}

notes

  1. 中看到它 Wayback Machine
  2. 同样在 github

Try the next:

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

If the above doesn't work, various projects have been added the following class: ClassLoaderUtil1 (code here).2

Here are some examples of how that class is used:

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
}

Notes

  1. See it in The Wayback Machine.
  2. Also in GitHub.
暮凉 2025-02-20 03:24:08

尝试:

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

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

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

Try:

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

IIRC getResourceAsStream() by default is relative to the class's package.

As @Terran noted, don't forget to add the / at the starting of the filename

随心而道 2025-02-20 03:24:08

尝试遵循春季项目

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

Try following codes on Spring project

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

Or on non spring project

 ClassLoader classLoader = getClass().getClassLoader();
 File file = new File(classLoader.getResource("fileName").getFile());
 InputStream inputStream = new FileInputStream(file);
囚你心 2025-02-20 03:24:08

这是一个快速解决方案,使用 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)

Here is one quick solution with the use of 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);
}

Usage:

String fixture = this.readResource("filename.txt", Charsets.UTF_8)
避讳 2025-02-20 03:24:08

非春季项目:

String filePath = Objects.requireNonNull(getClass().getClassLoader().getResource("any.json")).getPath();

Stream<String> lines = Files.lines(Paths.get(filePath));

或者

String filePath = Objects.requireNonNull(getClass().getClassLoader().getResource("any.json")).getPath();

InputStream in = new FileInputStream(filePath);

对于春季项目,您还可以使用一个行代码在Resources文件夹下获取任何文件:

File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "any.json");

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

Non spring project:

String filePath = Objects.requireNonNull(getClass().getClassLoader().getResource("any.json")).getPath();

Stream<String> lines = Files.lines(Paths.get(filePath));

Or

String filePath = Objects.requireNonNull(getClass().getClassLoader().getResource("any.json")).getPath();

InputStream in = new FileInputStream(filePath);

For spring projects, you can also use one line code to get any file under resources folder:

File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "any.json");

String content = new String(Files.readAllBytes(file.toPath()));
天煞孤星 2025-02-20 03:24:08

对于Java 1.7

 List<String> lines = Files.readAllLines(Paths.get(getClass().getResource("test.csv").toURI()));

另外,如果您在Spring Echosystem中可以使用Spring Utils,可以使用Spring

final val file = ResourceUtils.getFile("classpath:json/abcd.json");

Utils,以了解更多现场,请在博客

https://todzhang.com/blogs/tech/en/save_resources_to_files

For java after 1.7

 List<String> lines = Files.readAllLines(Paths.get(getClass().getResource("test.csv").toURI()));

Alternatively you can use Spring utils if you are in Spring echosystem

final val file = ResourceUtils.getFile("classpath:json/abcd.json");

To get to more behind the scene, check out following blog

https://todzhang.com/blogs/tech/en/save_resources_to_files

哆啦不做梦 2025-02-20 03:24:08

我面对同一问题

该文件是由类加载程序找到的,这意味着它没有包装到工件中(JAR)。您需要构建项目。例如,使用Maven:

mvn clean package

因此,您添加到Resources文件夹的文件将进入Maven构建,并可用于应用程序。

我想保持答案:它没有解释如何读取文件(其他答案确实解释了),它回答为什么 inputStream 资源>代码>是 null 。类似答案在这里

I faced the same issue.

The file was not found by a class loader, which means it was not packed into the artifact (jar). You need to build the project. For example, with maven:

mvn clean package

So the files you added to resources folder will get into maven build and become available to the application.

I would like to keep my answer: it does not explain how to read a file (other answers do explain that), it answers why InputStream or resource was null. Similar answer is here.

一杯敬自由 2025-02-20 03:24:08
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("test.csv");

如果您使用上下文classloader查找资源,那么它肯定会花费应用程序性能。

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

If you use context ClassLoader to find a resource then definitely it will cost application performance.

云柯 2025-02-20 03:24:08

现在,我说明了读取Maven创建资源目录的字体的源代码,

scr/main/resources/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;
}

​你,享受!

Now I am illustrating the source code for reading a font from maven created resources directory,

scr/main/resources/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;
}

It worked for me and hope that the entire source code will also help you, Enjoy!

忆离笙 2025-02-20 03:24:08

导入以下内容:

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

Import the following:

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

The following method returns a file in an ArrayList of Strings:

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;
}
醉生梦死 2025-02-20 03:24:08

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

You can use the com.google.common.io.Resources.getResource to read the url of file and then get the file content using java.nio.file.Files to read the content of file.

URL urlPath = Resources.getResource("src/main/resource");
List<String> multilineContent= Files.readAllLines(Paths.get(urlPath.toURI()));
夜无邪 2025-02-20 03:24:08

如果要以静态方法加载文件,则
classloader classloader = getClass()。getClassloader();
这可能会给您带来错误。

你可以尝试这个
例如,您要从资源加载的文件是资源&gt;&gt;图像&gt;&gt; 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();

if you are loading file in static method then
ClassLoader classLoader = getClass().getClassLoader();
this might give you an error.

You can try this
e.g. file you want to load from resources is 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();
携君以终年 2025-02-20 03:24:08

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

getResource() was working fine with the resources files placed in src/main/resources only. To get a file which is at the path other than src/main/resources say src/test/java you need to create it exlicitly.

the following example may help you

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")));
    }
}
殤城〤 2025-02-20 03:24:08
this.getClass().getClassLoader().getResource("filename").getPath()
this.getClass().getClassLoader().getResource("filename").getPath()
弥枳 2025-02-20 03:24:08

要从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());

To read the files from src/resources folder then try this :

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

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

in case of non static reference:

return new File(getClass().getClassLoader().getResource(fileName).getFile());
So要识趣 2025-02-20 03:24:08

对于Kotlin,我正在做以下操作:

  1. 我在项目中创建了一个资产文件夹
    (对于Android Studio,转到文件 - &gt; new-&gt; folder - &gt; Assets文件夹)
  2. 将我的资产(.txt文件)复制到此文件夹中
  3. ,然后我使用下面的代码

导入这些项目:

    import android.content.Context
    import android.util.Log
    import java.io.FileNotFoundException

我创建了这样的函数:这​​样:

    fun loadBook(context: Context) {
       val assetManager = context.assets
       try {
          val inputStream = assetManager?.open("19-Psalms.usfm")
          val lineList = mutableListOf<String>()

          inputStream?.bufferedReader()?.forEachLine { lineList.add(it) }
          lineList.forEach{println(">  $it")}
      }
      catch (e:FileNotFoundException) {
          Log.e("FileNotFoundException","File not found")
      }
    }
 

For Kotlin I am doing the following:

  1. I created an assets folder in my project
    (for Android studio go to File -> New-> Folder -> Assets Folder)
  2. Copied my assets (.txt files) to this folder
  3. Then I used the code below

Import these items:

    import android.content.Context
    import android.util.Log
    import java.io.FileNotFoundException

I created a function like this:

    fun loadBook(context: Context) {
       val assetManager = context.assets
       try {
          val inputStream = assetManager?.open("19-Psalms.usfm")
          val lineList = mutableListOf<String>()

          inputStream?.bufferedReader()?.forEachLine { lineList.add(it) }
          lineList.forEach{println(">  $it")}
      }
      catch (e:FileNotFoundException) {
          Log.e("FileNotFoundException","File not found")
      }
    }
 
望喜 2025-02-20 03:24:08

例如,从IDE运行时,该代码在不运行maven-build jar时是否有效?如果是这样,请确保文件实际上包含在JAR中。资源文件夹应包含在&lt;构建中的POM文件中。

Does the code work when not running the Maven-build jar, for example when running from your IDE? If so, make sure the file is actually included in the jar. The resources folder should be included in the pom file, in <build><resources>.

和我恋爱吧 2025-02-20 03:24:08

以下类可用于从 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;
    }
}

The following class can be used to load a resource from the classpath and also receive a fitting error message in case there's a problem with the given 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;
    }
}
上课铃就是安魂曲 2025-02-20 03:24:08

即使我遵循答案,也找不到我在测试文件夹中的文件。它通过重建项目来解决。似乎Intellij并未自动识别新文件。很讨厌找出答案。

My file in the test folder could not be found even though I followed the answers. It got resolved by rebuilding the project. It seems IntelliJ did not recognize the new file automatically. Pretty nasty to find out.

救赎№ 2025-02-20 03:24:08

我通过写作作为在运行罐子和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);

I got it work on both running jar and in IDE by writing as

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);
琉璃梦幻 2025-02-20 03:24:08

我目前正在这样做。

这是我的结构。

final String path =   "src/test/resources/archivos/B-163.txt";
final Path filePath = Path.of( path );
final String documento = Files.readString( filePath );
         
log.debug("DOCUMENTO: {}" , document); 

我正在与Java 11一起工作。

I am currently doing it this way.

This is my structure.
enter image description here

final String path =   "src/test/resources/archivos/B-163.txt";
final Path filePath = Path.of( path );
final String documento = Files.readString( filePath );
         
log.debug("DOCUMENTO: {}" , document); 

I am working with Java 11.

北恋 2025-02-20 03:24:08

对于Kotlin:

import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths

val lines = Files.readAllLines(
    Paths.get((object {}).javaClass.getResource("videos.txt").toURI()),
    StandardCharsets.UTF_8
)

lines // will contain list of lines in a file

For Kotlin:

import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths

val lines = Files.readAllLines(
    Paths.get((object {}).javaClass.getResource("videos.txt").toURI()),
    StandardCharsets.UTF_8
)

lines // will contain list of lines in a file
凝望流年 2025-02-20 03:24:08

如果要获取文件对象:

File file = new File(this.getClass().getClassLoader().getResource("test.csv").toURI())

If you want to get a File object:

File file = new File(this.getClass().getClassLoader().getResource("test.csv").toURI())
蓝眸 2025-02-20 03:24:08

从资源文件夹中加载文件作为流,

以便在资源文件夹中访问文件,您应该使用方法

// From non-static context
InputStream is = getClass().getClassLoader().getResourceAsStream("test.txt");

// From static context
InputStream is = MyClass.class.getClassLoader().getResourceAsStream("test.txt");

无论您的应用程序正在开发,测试还是构建,这种方法都可以访问资源。实际上,当使用Maven或Gradle等构建工具时,将资源从 ../ src/main/resources 复制到 target/class/class 构建的根部/类。基本上, getResourCeasStream()方法以独立于代码的位置的方式授予您通过类代码访问资源

从资源文件夹中加载文件java.io.file

或者,如果您需要一个 java.io.file ,您可以使用 方法将资源检索为 url ,并创建一个文件来自资源路径或URI。但是,使用URI需要处理 urisyntaxexception

// From non-static context
File f1 = new File(getClass().getClassLoader().getResource("test.txt").getPath());
File f2 = new File(getClass().getClassLoader().getResource("test.txt").toURI());

// From static context
File f1 = new File(MyClass.class.getClassLoader().getResource("test.txt").getPath());
File f2 = new File(MyClass.class.getClassLoader().getResource("test.txt").toURI());

从资源文件夹加载文件java.nio.file.path

,如果您需要一个 java.nio.file.path ,您可以使用静态方法 path.of() (来自JDK 11)带有资源URI的路径

// From non-static context
Path p = Path.of(getClass().getClassLoader().getResource("test.txt").toURI());

// From static context
Path p = Path.of(Main.class.getClassLoader().getResource("test.txt").toURI());

Load File from Resource Folder as Stream

To generically access a file in a resource folder, you should use the method getResourceAsStream().

// From non-static context
InputStream is = getClass().getClassLoader().getResourceAsStream("test.txt");

// From static context
InputStream is = MyClass.class.getClassLoader().getResourceAsStream("test.txt");

This approach allows you to access a resource whether your application is being developed, tested or built. In fact, when using build tools like Maven or Gradle, resources are copied from ../src/main/resources to the root of target/classes or build/classes. Basically, the getResourceAsStream() method grants you to access a resource by class code in a way that is independent of the location of the code.

Load File from Resource Folder as java.io.File

Alternatively, if you need an instance of java.io.File, you can employ the getResource() method to retrieve the resource as a URL, and create a File from the resource's path or URI. However, using the URI requires handling the URISyntaxException.

// From non-static context
File f1 = new File(getClass().getClassLoader().getResource("test.txt").getPath());
File f2 = new File(getClass().getClassLoader().getResource("test.txt").toURI());

// From static context
File f1 = new File(MyClass.class.getClassLoader().getResource("test.txt").getPath());
File f2 = new File(MyClass.class.getClassLoader().getResource("test.txt").toURI());

Load File from Resource Folder as java.nio.file.Path

Instead, if you need an instance of java.nio.file.Path, you can employ the static method Path.of() (from JDK 11) to build a Path with the resource's URI.

// From non-static context
Path p = Path.of(getClass().getClassLoader().getResource("test.txt").toURI());

// From static context
Path p = Path.of(Main.class.getClassLoader().getResource("test.txt").toURI());
转角预定愛 2025-02-20 03:24:08

这对我来说很好:

InputStream in = getClass().getResourceAsStream("/main/resources/xxx.xxx");
InputStreamReader streamReader = new InputStreamReader(in, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(streamReader);
String content = "";
for (String line; (line = reader.readLine()) != null;) {
    content += line;
}

This worked pretty fine for me :

InputStream in = getClass().getResourceAsStream("/main/resources/xxx.xxx");
InputStreamReader streamReader = new InputStreamReader(in, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(streamReader);
String content = "";
for (String line; (line = reader.readLine()) != null;) {
    content += line;
}
时光倒影 2025-02-20 03:24:08

我可以将其工作起作用,而无需提及“类”或“ ClassLoader”。

假设我们有三种情况,即文件“示例”的位置,您的工作目录(您的应用程序执行)是Home/myDocuments/program/projection/myapp:

a)工作目录的子文件夹后代:
myApp/res/files/xplove.file

b)一个非后代的子文件夹:工作目录:
projects/files/example.file

b2)另一个子文件夹不是工作目录的后代:
程序/文件/示例。文件

c)根文件夹:
home/mydocuments/files/example.file(linux;在Windows中替换为Home/c :)

1)获取正确的路径:
a)字符串路径=“ res/files/example.file”;
b)字符串路径=“ ../ projects/files/example.file”
b2)字符串路径=“ ../../ program/files/example.file”
c)字符串路径=“/home/mydocuments/files/example.file”

基本上,如果它是根文件夹,请使用领先的斜杠启动路径名。
如果是子文件夹,则不得在路径名之前进行斜杠。如果子文件夹不是工作目录的后代,则必须使用“ ../”来cd。这告诉系统上一个文件夹。

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

File file = new File(path);

3)您现在很好:

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

I get it to work without any reference to "class" or "ClassLoader".

Let's say we have three scenarios with the location of the file 'example.file' and your working directory (where your app executes) is home/mydocuments/program/projects/myapp:

a)A sub folder descendant to the working directory:
myapp/res/files/example.file

b)A sub folder not descendant to the working directory:
projects/files/example.file

b2)Another sub folder not descendant to the working directory:
program/files/example.file

c)A root folder:
home/mydocuments/files/example.file (Linux; in Windows replace home/ with C:)

1) Get the right path:
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"

Basically, if it is a root folder, start the path name with a leading slash.
If it is a sub folder, no slash must be before the path name. If the sub folder is not descendant to the working directory you have to cd to it using "../". This tells the system to go up one folder.

2) Create a File object by passing the right path:

File file = new File(path);

3) You are now good to go:

BufferedReader br = new BufferedReader(new FileReader(file));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文