I am trying to read a text file which is set in CLASSPATH system variable. Not a user variable.
我正在尝试读取一个在CLASSPATH系统变量中设置的文本文件。不是一个用户变量。
I am trying to get input stream to the file as below:
我正在尝试将输入流输入到文件中,如下所示:
Place the directory of file (D:\myDir
)in CLASSPATH and try below:
将文件目录(D:\myDir)放在类路径中,并尝试如下:
InputStream in = this.getClass().getClassLoader().getResourceAsStream("SomeTextFile.txt");
InputStream in = this.getClass().getClassLoader().getResourceAsStream("/SomeTextFile.txt");
InputStream in = this.getClass().getClassLoader().getResourceAsStream("//SomeTextFile.txt");
Place full path of file (D:\myDir\SomeTextFile.txt
)in CLASSPATH and try the same above 3 lines of code.
在类路径中放置完整的文件路径(D: myDir\SomeTextFile.txt),并尝试以上3行代码。
But unfortunately NONE of them are working and I am always getting null
into my InputStream in
.
但不幸的是,它们都不起作用,我总是把null输入到InputStream中。
17 个解决方案
#1
506
With the directory on the classpath, from a class loaded by the same classloader, you should be able to use either of:
在类路径上的目录中,从同一个类加载器加载的类中,您应该可以使用以下任何一个:
// From ClassLoader, all paths are "absolute" already - there's no context
// from which they could be relative. Therefore you don't need a leading slash.
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("SomeTextFile.txt");
// From Class, the path is relative to the package of the class unless
// you include a leading slash, so if you don't want to use the current
// package, include a slash like this:
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
If those aren't working, that suggests something else is wrong.
如果这些都不起作用,那就说明还有别的问题。
So for example, take this code:
举个例子,这段代码
package dummy;
import java.io.*;
public class Test
{
public static void main(String[] args)
{
InputStream stream = Test.class.getResourceAsStream("/SomeTextFile.txt");
System.out.println(stream != null);
stream = Test.class.getClassLoader().getResourceAsStream("SomeTextFile.txt");
System.out.println(stream != null);
}
}
And this directory structure:
这目录结构:
code
dummy
Test.class
txt
SomeTextFile.txt
And then (using the Unix path separator as I'm on a Linux box):
然后(使用Unix路径分隔符,就像我在Linux机器上一样):
java -classpath code:txt dummy.Test
Results:
结果:
true
true
#2
101
When using the Spring Framework (either as a collection of utilities or container - you do not need to use the latter functionality) you can easily use the Resource abstraction.
在使用Spring框架(作为实用程序或容器的集合——不需要使用后一种功能)时,可以轻松地使用资源抽象。
Resource resource = new ClassPathResource("com/example/Foo.class");
Through the Resource interface you can access the resource as InputStream, URL, URI or File. Changing the resource type to e.g. a file system resource is a simple matter of changing the instance.
通过资源接口,您可以以InputStream、URL、URI或文件的形式访问资源。将资源类型更改为,例如,文件系统资源是简单地更改实例。
#3
39
This is how I read all lines of a text file on my classpath, using Java 7 NIO:
这就是我使用Java 7 NIO读取类路径上所有文本文件的方式:
...
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
...
Files.readAllLines(
Paths.get(this.getClass().getResource("res.txt").toURI()), Charset.defaultCharset());
NB this is an example of how it can be done. You'll have to make improvements as necessary. This example will only work if the file is actually present on your classpath, otherwise a NullPointerException will be thrown when getResource() returns null and .toURI() is invoked on it.
这是如何做到的一个例子。你必须根据需要进行改进。此示例仅在该文件实际出现在类路径上时才有效,否则当getResource()返回null并在其上调用. touri()时将抛出NullPointerException。
Also, since Java 7, one convenient way of specifying character sets is to use the constants defined in java.nio.charset.StandardCharsets
(these are, according to their javadocs, "guaranteed to be available on every implementation of the Java platform.").
而且,自从Java 7以来,指定字符集的一种方便方法是使用Java .nio.charset中定义的常量。标准字符集(根据它们的javadocs,它们“保证在Java平台的每个实现上都可用”)。
Hence, if you know the encoding of the file to be UTF-8, then specify explicitly the charset StandardCharsets.UTF_8
因此,如果您知道文件的编码是UTF-8,那么要显式地指定字符集standard . utf_8
#4
22
Please try
请尝试
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
Your tries didn't work because only the class loader for your classes is able to load from the classpath. You used the class loader for the java system itself.
您的尝试没有成功,因为只有类的类装入器可以从类路径中装入。您使用了java系统本身的类装入器。
#5
15
To actually read the contents of the file, I like using Commons IO + Spring Core. Assuming Java 8:
要实际读取文件的内容,我喜欢使用Commons IO + Spring Core。假设Java 8:
try (InputStream stream = new ClassPathResource("package/resource").getInputStream()) {
IOUtils.toString(stream);
}
Alternatively:
另外:
InputStream stream = null;
try {
stream = new ClassPathResource("/log4j.xml").getInputStream();
IOUtils.toString(stream);
} finally {
IOUtils.closeQuietly(stream);
}
#6
12
To get the class absolute path try this:
要获得类的绝对路径,请尝试以下方法:
String url = this.getClass().getResource("").getPath();
#7
10
Somehow the best answer doesn't work for me. I need to use a slightly different code instead.
不知何故,最好的答案对我不起作用。我需要使用稍微不同的代码。
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("SomeTextFile.txt");
I hope this help those who encounters the same issue.
我希望这能帮助那些遇到同样问题的人。
#8
4
If you use Guava:
如果你使用番石榴:
import com.google.common.io.Resources;
we can get URL from CLASSPATH:
我们可以从类路径获取URL:
URL resource = Resources.getResource("test.txt");
String file = resource.getFile(); // get file path
or InputStream:
或InputStream:
InputStream is = Resources.getResource("test.txt").openStream();
#9
2
To read the contents of a file into a String from the classpath
, you can use this:
要从类路径中读取文件的内容,可以使用以下方法:
private String resourceToString(String filePath) throws IOException, URISyntaxException
{
try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath))
{
return IOUtils.toString(inputStream);
}
}
Note:IOUtils
is part of Commons IO
.
注意:IOUtils是Commons IO的一部分。
Call it like this:
叫它是这样的:
String fileContents = resourceToString("ImOnTheClasspath.txt");
#10
1
You say "I am trying to read a text file which is set in CLASSPATH system variable." My guess this is on Windows and you are using this ugly dialog to edit the "System Variables".
您说“我正在尝试读取类路径系统变量中设置的文本文件”。我猜这是在Windows上,你正在用这个难看的对话框编辑“系统变量”。
Now you run your Java program in the console. And that doesn't work: The console gets a copy of the values of the system variables once when it is started. This means any change in the dialog afterwards doesn't have any effect.
现在,您可以在控制台中运行Java程序。这是行不通的:控制台在启动时获得系统变量的值的副本。这意味着之后对话框中的任何改变都没有任何效果。
There are these solutions:
这些解决方案:
-
Start a new console after every change
每次更改后启动一个新的控制台
-
Use
set CLASSPATH=...
in the console to set the copy of the variable in the console and when your code works, paste the last value into the variable dialog.使用设置CLASSPATH =…在控制台中设置控制台中变量的拷贝,当代码工作时,将最后一个值粘贴到变量对话框中。
-
Put the call to Java into
.BAT
file and double click it. This will create a new console every time (thus copying the current value of the system variable).将对Java的调用放入. bat文件并双击它。这将每次创建一个新的控制台(因此复制系统变量的当前值)。
BEWARE: If you also have a User variable CLASSPATH
then it will shadow your system variable. That is why it is usually better to put the call to your Java program into a .BAT
file and set the classpath in there (using set CLASSPATH=
) rather than relying on a global system or user variable.
注意:如果您也有一个用户变量类路径,那么它将影响系统变量。这就是为什么将对Java程序的调用放入. bat文件并在其中设置类路径(使用set classpath =),而不是依赖全局系统或用户变量,通常是更好的方法。
This also makes sure that you can have more than one Java program working on your computer because they are bound to have different classpaths.
这还确保您可以在您的计算机上使用多个Java程序,因为它们一定有不同的类路径。
#11
0
Whenever you add a directory to the classpath, all the resources defined under it will be copied directly under the deployment folder of the application (e.g. bin).
当您向类路径添加目录时,它下定义的所有资源将直接复制到应用程序的部署文件夹(例如bin)下。
In order to access a resource from your application, you can use '/' prefix which points to the root path of the deployment folder, the other parts of the path depends on the location of your resource (whether it's directly under "D:\myDir" or nested under a subfolder)
为了从应用程序访问资源,可以使用“/”前缀指向部署文件夹的根路径,路径的其他部分取决于资源的位置(无论是直接在“D:\myDir”下还是在子文件夹下嵌套)
Check this tutorial for more information.
查看本教程了解更多信息。
In your example, you should be able to access your resource through the following:
在您的示例中,您应该能够通过以下方式访问您的资源:
InputStream is = getClass().getResourceAsStream("/SomeTextFile.txt");
Knowing that "SomeTextFile.txt" exists directly under "D:\myDir"
知道“SomeTextFile。txt"直接存在于"D:\myDir"下
#12
0
Use org.apache.commons.io.FileUtils.readFileToString(new File("src/test/resources/sample-data/fileName.txt"));
使用org.apache.commons.io.FileUtils.readFileToString(新文件(“src /测试/资源/采样数据/ fileName.txt "));
#13
0
Scenario:
场景:
1) client-service-1.0-SNAPSHOT.jar
has dependency read-classpath-resource-1.0-SNAPSHOT.jar
1)客户端-服务- 1.0 -快照。jar依赖阅读-路径-资源- 1.0 - snapshot.jar
2) we want to read content of class path resources (sample.txt
) of read-classpath-resource-1.0-SNAPSHOT.jar
through client-service-1.0-SNAPSHOT.jar
.
2)我们要读取read-classpath-resource-1.0 snapshot的类路径资源(sample.txt)的内容。通过客户端-服务- 1.0 snapshot.jar jar。
3) read-classpath-resource-1.0-SNAPSHOT.jar
has src/main/resources/sample.txt
3)读-路径-资源- 1.0 -快照。jar主要有src / /资源/ sample.txt
Here is working sample code I prepared, after 2-3days wasting my development time, I found the complete end-to-end solution, hope this helps to save your time
这是我准备的工作示例代码,在浪费了2-3天的开发时间之后,我找到了完整的端到端解决方案,希望这有助于节省您的时间
1.pom.xml
of read-classpath-resource-1.0-SNAPSHOT.jar
1.砰的一声。xml的读-路径-资源- 1.0 - snapshot.jar
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>jar-classpath-resource</groupId>
<artifactId>read-classpath-resource</artifactId>
<version>1.0-SNAPSHOT</version>
<name>classpath-test</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework.version>4.3.3.RELEASE</org.springframework.version>
<mvn.release.plugin>2.5.1</mvn.release.plugin>
<output.path>${project.artifactId}</output.path>
<io.dropwizard.version>1.0.3</io.dropwizard.version>
<commons-io.verion>2.4</commons-io.verion>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.verion}</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>${mvn.release.plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.5</version>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<useUniqueVersions>false</useUniqueVersions>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<mainClass>demo.read.classpath.resources.ClassPathResourceReadTest</mainClass>
</manifest>
<manifestEntries>
<Implementation-Artifact-Id>${project.artifactId}</Implementation-Artifact-Id>
<Class-Path>sample.txt</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.2</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>demo.read.classpath.resources.ClassPathResourceReadTest</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
2.ClassPathResourceReadTest.java
class in read-classpath-resource-1.0-SNAPSHOT.jar
that loads the class path resources file content.
2. classpathresourcereadtest。java类在阅读-路径-资源- 1.0 -快照。jar装载类路径资源文件内容。
package demo.read.classpath.resources;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public final class ClassPathResourceReadTest {
public ClassPathResourceReadTest() throws IOException {
InputStream inputStream = getClass().getResourceAsStream("/sample.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
List<Object> list = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
list.add(line);
}
for (Object s1: list) {
System.out.println("@@@ " +s1);
}
System.out.println("getClass().getResourceAsStream('/sample.txt') lines: "+list.size());
}
}
3.pom.xml
of client-service-1.0-SNAPSHOT.jar
3.砰的一声。xml的客户-服务- 1.0 - snapshot.jar
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>client-service</groupId>
<artifactId>client-service</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>jar-classpath-resource</groupId>
<artifactId>read-classpath-resource</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.5</version>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<useUniqueVersions>false</useUniqueVersions>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<mainClass>com.crazy.issue.client.AccessClassPathResource</mainClass>
</manifest>
<manifestEntries>
<Implementation-Artifact-Id>${project.artifactId}</Implementation-Artifact-Id>
<Implementation-Source-SHA>${buildNumber}</Implementation-Source-SHA>
<Class-Path>sample.txt</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.2</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.crazy.issue.client.AccessClassPathResource</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
4.AccessClassPathResource.java
instantiate ClassPathResourceReadTest.java
class where, it is going to load sample.txt
and prints its content also.
4. accessclasspathresource。java实例化ClassPathResourceReadTest。java类中,它将加载sample。txt并打印其内容。
package com.crazy.issue.client;
import demo.read.classpath.resources.ClassPathResourceReadTest;
import java.io.IOException;
public class AccessClassPathResource {
public static void main(String[] args) throws IOException {
ClassPathResourceReadTest test = new ClassPathResourceReadTest();
}
}
5.Run Executable jar as follows:
5。运行可执行jar如下:
[ravibeli@localhost lib]$ java -jar client-service-1.0-SNAPSHOT.jar
****************************************
I am in resources directory of read-classpath-resource-1.0-SNAPSHOT.jar
****************************************
3) getClass().getResourceAsStream('/sample.txt'): 3
#14
-1
I am using webshpere application server and my Web Module is build on Spring MVC. The Test.properties
were located in the resources folder, i tried to load this files using the following:
我正在使用webshpere应用服务器,我的Web模块构建在Spring MVC之上。测试。属性位于resources文件夹中,我尝试使用以下方法加载此文件:
-
this.getClass().getClassLoader().getResourceAsStream("Test.properties");
- .getResourceAsStream .getClassLoader this.getClass()()(“Test.properties”);
this.getClass().getResourceAsStream("/Test.properties");
- this.getClass().getResourceAsStream(" / Test.properties ");
None of the above code loaded the file.
以上代码均未加载该文件。
But with the help of below code the property file was loaded successfully:
但在以下代码的帮助下,成功加载了属性文件:
Thread.currentThread().getContextClassLoader().getResourceAsStream("Test.properties");
.getResourceAsStream .getContextClassLoader Thread.currentThread()()(“Test.properties”);
Thanks to the user "user1695166".
感谢用户“user1695166”。
#15
-2
Don't use getClassLoader() method and use the "/" before the file name. "/" is very important
不要使用getClassLoader()方法,在文件名之前使用“/”。“/”是非常重要的
this.getClass().getResourceAsStream("/SomeTextFile.txt");
#16
-4
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile
{
/**
* * feel free to make any modification I have have been here so I feel you
* * * @param args * @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// thread pool of 10
File dir = new File(".");
// read file from same directory as source //
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
// if you wanna read file name with txt files
if (file.getName().contains("txt")) {
System.out.println(file.getName());
}
// if you want to open text file and read each line then
if (file.getName().contains("txt")) {
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(
file.getAbsolutePath());
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(
fileReader);
String line;
// get file details and get info you need.
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
// here you can say...
// System.out.println(line.substring(0, 10)); this
// prints from 0 to 10 indext
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '"
+ file.getName() + "'");
} catch (IOException ex) {
System.out.println("Error reading file '"
+ file.getName() + "'");
// Or we could just do this:
ex.printStackTrace();
}
}
}
}
}
}
#17
-5
you have to put your 'system variable' on the java classpath.
您必须将“系统变量”放在java类路径中。
#1
506
With the directory on the classpath, from a class loaded by the same classloader, you should be able to use either of:
在类路径上的目录中,从同一个类加载器加载的类中,您应该可以使用以下任何一个:
// From ClassLoader, all paths are "absolute" already - there's no context
// from which they could be relative. Therefore you don't need a leading slash.
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("SomeTextFile.txt");
// From Class, the path is relative to the package of the class unless
// you include a leading slash, so if you don't want to use the current
// package, include a slash like this:
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
If those aren't working, that suggests something else is wrong.
如果这些都不起作用,那就说明还有别的问题。
So for example, take this code:
举个例子,这段代码
package dummy;
import java.io.*;
public class Test
{
public static void main(String[] args)
{
InputStream stream = Test.class.getResourceAsStream("/SomeTextFile.txt");
System.out.println(stream != null);
stream = Test.class.getClassLoader().getResourceAsStream("SomeTextFile.txt");
System.out.println(stream != null);
}
}
And this directory structure:
这目录结构:
code
dummy
Test.class
txt
SomeTextFile.txt
And then (using the Unix path separator as I'm on a Linux box):
然后(使用Unix路径分隔符,就像我在Linux机器上一样):
java -classpath code:txt dummy.Test
Results:
结果:
true
true
#2
101
When using the Spring Framework (either as a collection of utilities or container - you do not need to use the latter functionality) you can easily use the Resource abstraction.
在使用Spring框架(作为实用程序或容器的集合——不需要使用后一种功能)时,可以轻松地使用资源抽象。
Resource resource = new ClassPathResource("com/example/Foo.class");
Through the Resource interface you can access the resource as InputStream, URL, URI or File. Changing the resource type to e.g. a file system resource is a simple matter of changing the instance.
通过资源接口,您可以以InputStream、URL、URI或文件的形式访问资源。将资源类型更改为,例如,文件系统资源是简单地更改实例。
#3
39
This is how I read all lines of a text file on my classpath, using Java 7 NIO:
这就是我使用Java 7 NIO读取类路径上所有文本文件的方式:
...
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
...
Files.readAllLines(
Paths.get(this.getClass().getResource("res.txt").toURI()), Charset.defaultCharset());
NB this is an example of how it can be done. You'll have to make improvements as necessary. This example will only work if the file is actually present on your classpath, otherwise a NullPointerException will be thrown when getResource() returns null and .toURI() is invoked on it.
这是如何做到的一个例子。你必须根据需要进行改进。此示例仅在该文件实际出现在类路径上时才有效,否则当getResource()返回null并在其上调用. touri()时将抛出NullPointerException。
Also, since Java 7, one convenient way of specifying character sets is to use the constants defined in java.nio.charset.StandardCharsets
(these are, according to their javadocs, "guaranteed to be available on every implementation of the Java platform.").
而且,自从Java 7以来,指定字符集的一种方便方法是使用Java .nio.charset中定义的常量。标准字符集(根据它们的javadocs,它们“保证在Java平台的每个实现上都可用”)。
Hence, if you know the encoding of the file to be UTF-8, then specify explicitly the charset StandardCharsets.UTF_8
因此,如果您知道文件的编码是UTF-8,那么要显式地指定字符集standard . utf_8
#4
22
Please try
请尝试
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
Your tries didn't work because only the class loader for your classes is able to load from the classpath. You used the class loader for the java system itself.
您的尝试没有成功,因为只有类的类装入器可以从类路径中装入。您使用了java系统本身的类装入器。
#5
15
To actually read the contents of the file, I like using Commons IO + Spring Core. Assuming Java 8:
要实际读取文件的内容,我喜欢使用Commons IO + Spring Core。假设Java 8:
try (InputStream stream = new ClassPathResource("package/resource").getInputStream()) {
IOUtils.toString(stream);
}
Alternatively:
另外:
InputStream stream = null;
try {
stream = new ClassPathResource("/log4j.xml").getInputStream();
IOUtils.toString(stream);
} finally {
IOUtils.closeQuietly(stream);
}
#6
12
To get the class absolute path try this:
要获得类的绝对路径,请尝试以下方法:
String url = this.getClass().getResource("").getPath();
#7
10
Somehow the best answer doesn't work for me. I need to use a slightly different code instead.
不知何故,最好的答案对我不起作用。我需要使用稍微不同的代码。
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("SomeTextFile.txt");
I hope this help those who encounters the same issue.
我希望这能帮助那些遇到同样问题的人。
#8
4
If you use Guava:
如果你使用番石榴:
import com.google.common.io.Resources;
we can get URL from CLASSPATH:
我们可以从类路径获取URL:
URL resource = Resources.getResource("test.txt");
String file = resource.getFile(); // get file path
or InputStream:
或InputStream:
InputStream is = Resources.getResource("test.txt").openStream();
#9
2
To read the contents of a file into a String from the classpath
, you can use this:
要从类路径中读取文件的内容,可以使用以下方法:
private String resourceToString(String filePath) throws IOException, URISyntaxException
{
try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath))
{
return IOUtils.toString(inputStream);
}
}
Note:IOUtils
is part of Commons IO
.
注意:IOUtils是Commons IO的一部分。
Call it like this:
叫它是这样的:
String fileContents = resourceToString("ImOnTheClasspath.txt");
#10
1
You say "I am trying to read a text file which is set in CLASSPATH system variable." My guess this is on Windows and you are using this ugly dialog to edit the "System Variables".
您说“我正在尝试读取类路径系统变量中设置的文本文件”。我猜这是在Windows上,你正在用这个难看的对话框编辑“系统变量”。
Now you run your Java program in the console. And that doesn't work: The console gets a copy of the values of the system variables once when it is started. This means any change in the dialog afterwards doesn't have any effect.
现在,您可以在控制台中运行Java程序。这是行不通的:控制台在启动时获得系统变量的值的副本。这意味着之后对话框中的任何改变都没有任何效果。
There are these solutions:
这些解决方案:
-
Start a new console after every change
每次更改后启动一个新的控制台
-
Use
set CLASSPATH=...
in the console to set the copy of the variable in the console and when your code works, paste the last value into the variable dialog.使用设置CLASSPATH =…在控制台中设置控制台中变量的拷贝,当代码工作时,将最后一个值粘贴到变量对话框中。
-
Put the call to Java into
.BAT
file and double click it. This will create a new console every time (thus copying the current value of the system variable).将对Java的调用放入. bat文件并双击它。这将每次创建一个新的控制台(因此复制系统变量的当前值)。
BEWARE: If you also have a User variable CLASSPATH
then it will shadow your system variable. That is why it is usually better to put the call to your Java program into a .BAT
file and set the classpath in there (using set CLASSPATH=
) rather than relying on a global system or user variable.
注意:如果您也有一个用户变量类路径,那么它将影响系统变量。这就是为什么将对Java程序的调用放入. bat文件并在其中设置类路径(使用set classpath =),而不是依赖全局系统或用户变量,通常是更好的方法。
This also makes sure that you can have more than one Java program working on your computer because they are bound to have different classpaths.
这还确保您可以在您的计算机上使用多个Java程序,因为它们一定有不同的类路径。
#11
0
Whenever you add a directory to the classpath, all the resources defined under it will be copied directly under the deployment folder of the application (e.g. bin).
当您向类路径添加目录时,它下定义的所有资源将直接复制到应用程序的部署文件夹(例如bin)下。
In order to access a resource from your application, you can use '/' prefix which points to the root path of the deployment folder, the other parts of the path depends on the location of your resource (whether it's directly under "D:\myDir" or nested under a subfolder)
为了从应用程序访问资源,可以使用“/”前缀指向部署文件夹的根路径,路径的其他部分取决于资源的位置(无论是直接在“D:\myDir”下还是在子文件夹下嵌套)
Check this tutorial for more information.
查看本教程了解更多信息。
In your example, you should be able to access your resource through the following:
在您的示例中,您应该能够通过以下方式访问您的资源:
InputStream is = getClass().getResourceAsStream("/SomeTextFile.txt");
Knowing that "SomeTextFile.txt" exists directly under "D:\myDir"
知道“SomeTextFile。txt"直接存在于"D:\myDir"下
#12
0
Use org.apache.commons.io.FileUtils.readFileToString(new File("src/test/resources/sample-data/fileName.txt"));
使用org.apache.commons.io.FileUtils.readFileToString(新文件(“src /测试/资源/采样数据/ fileName.txt "));
#13
0
Scenario:
场景:
1) client-service-1.0-SNAPSHOT.jar
has dependency read-classpath-resource-1.0-SNAPSHOT.jar
1)客户端-服务- 1.0 -快照。jar依赖阅读-路径-资源- 1.0 - snapshot.jar
2) we want to read content of class path resources (sample.txt
) of read-classpath-resource-1.0-SNAPSHOT.jar
through client-service-1.0-SNAPSHOT.jar
.
2)我们要读取read-classpath-resource-1.0 snapshot的类路径资源(sample.txt)的内容。通过客户端-服务- 1.0 snapshot.jar jar。
3) read-classpath-resource-1.0-SNAPSHOT.jar
has src/main/resources/sample.txt
3)读-路径-资源- 1.0 -快照。jar主要有src / /资源/ sample.txt
Here is working sample code I prepared, after 2-3days wasting my development time, I found the complete end-to-end solution, hope this helps to save your time
这是我准备的工作示例代码,在浪费了2-3天的开发时间之后,我找到了完整的端到端解决方案,希望这有助于节省您的时间
1.pom.xml
of read-classpath-resource-1.0-SNAPSHOT.jar
1.砰的一声。xml的读-路径-资源- 1.0 - snapshot.jar
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>jar-classpath-resource</groupId>
<artifactId>read-classpath-resource</artifactId>
<version>1.0-SNAPSHOT</version>
<name>classpath-test</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework.version>4.3.3.RELEASE</org.springframework.version>
<mvn.release.plugin>2.5.1</mvn.release.plugin>
<output.path>${project.artifactId}</output.path>
<io.dropwizard.version>1.0.3</io.dropwizard.version>
<commons-io.verion>2.4</commons-io.verion>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.verion}</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>${mvn.release.plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.5</version>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<useUniqueVersions>false</useUniqueVersions>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<mainClass>demo.read.classpath.resources.ClassPathResourceReadTest</mainClass>
</manifest>
<manifestEntries>
<Implementation-Artifact-Id>${project.artifactId}</Implementation-Artifact-Id>
<Class-Path>sample.txt</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.2</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>demo.read.classpath.resources.ClassPathResourceReadTest</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
2.ClassPathResourceReadTest.java
class in read-classpath-resource-1.0-SNAPSHOT.jar
that loads the class path resources file content.
2. classpathresourcereadtest。java类在阅读-路径-资源- 1.0 -快照。jar装载类路径资源文件内容。
package demo.read.classpath.resources;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public final class ClassPathResourceReadTest {
public ClassPathResourceReadTest() throws IOException {
InputStream inputStream = getClass().getResourceAsStream("/sample.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
List<Object> list = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
list.add(line);
}
for (Object s1: list) {
System.out.println("@@@ " +s1);
}
System.out.println("getClass().getResourceAsStream('/sample.txt') lines: "+list.size());
}
}
3.pom.xml
of client-service-1.0-SNAPSHOT.jar
3.砰的一声。xml的客户-服务- 1.0 - snapshot.jar
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>client-service</groupId>
<artifactId>client-service</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>jar-classpath-resource</groupId>
<artifactId>read-classpath-resource</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.5</version>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<useUniqueVersions>false</useUniqueVersions>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<mainClass>com.crazy.issue.client.AccessClassPathResource</mainClass>
</manifest>
<manifestEntries>
<Implementation-Artifact-Id>${project.artifactId}</Implementation-Artifact-Id>
<Implementation-Source-SHA>${buildNumber}</Implementation-Source-SHA>
<Class-Path>sample.txt</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.2</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.crazy.issue.client.AccessClassPathResource</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
4.AccessClassPathResource.java
instantiate ClassPathResourceReadTest.java
class where, it is going to load sample.txt
and prints its content also.
4. accessclasspathresource。java实例化ClassPathResourceReadTest。java类中,它将加载sample。txt并打印其内容。
package com.crazy.issue.client;
import demo.read.classpath.resources.ClassPathResourceReadTest;
import java.io.IOException;
public class AccessClassPathResource {
public static void main(String[] args) throws IOException {
ClassPathResourceReadTest test = new ClassPathResourceReadTest();
}
}
5.Run Executable jar as follows:
5。运行可执行jar如下:
[ravibeli@localhost lib]$ java -jar client-service-1.0-SNAPSHOT.jar
****************************************
I am in resources directory of read-classpath-resource-1.0-SNAPSHOT.jar
****************************************
3) getClass().getResourceAsStream('/sample.txt'): 3
#14
-1
I am using webshpere application server and my Web Module is build on Spring MVC. The Test.properties
were located in the resources folder, i tried to load this files using the following:
我正在使用webshpere应用服务器,我的Web模块构建在Spring MVC之上。测试。属性位于resources文件夹中,我尝试使用以下方法加载此文件:
-
this.getClass().getClassLoader().getResourceAsStream("Test.properties");
- .getResourceAsStream .getClassLoader this.getClass()()(“Test.properties”);
this.getClass().getResourceAsStream("/Test.properties");
- this.getClass().getResourceAsStream(" / Test.properties ");
None of the above code loaded the file.
以上代码均未加载该文件。
But with the help of below code the property file was loaded successfully:
但在以下代码的帮助下,成功加载了属性文件:
Thread.currentThread().getContextClassLoader().getResourceAsStream("Test.properties");
.getResourceAsStream .getContextClassLoader Thread.currentThread()()(“Test.properties”);
Thanks to the user "user1695166".
感谢用户“user1695166”。
#15
-2
Don't use getClassLoader() method and use the "/" before the file name. "/" is very important
不要使用getClassLoader()方法,在文件名之前使用“/”。“/”是非常重要的
this.getClass().getResourceAsStream("/SomeTextFile.txt");
#16
-4
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile
{
/**
* * feel free to make any modification I have have been here so I feel you
* * * @param args * @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// thread pool of 10
File dir = new File(".");
// read file from same directory as source //
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
// if you wanna read file name with txt files
if (file.getName().contains("txt")) {
System.out.println(file.getName());
}
// if you want to open text file and read each line then
if (file.getName().contains("txt")) {
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(
file.getAbsolutePath());
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(
fileReader);
String line;
// get file details and get info you need.
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
// here you can say...
// System.out.println(line.substring(0, 10)); this
// prints from 0 to 10 indext
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '"
+ file.getName() + "'");
} catch (IOException ex) {
System.out.println("Error reading file '"
+ file.getName() + "'");
// Or we could just do this:
ex.printStackTrace();
}
}
}
}
}
}
#17
-5
you have to put your 'system variable' on the java classpath.
您必须将“系统变量”放在java类路径中。