文
章
目
录
章
目
录
要在Java中从类路径(classpath)中读取文件,可以遵循以下步骤:
1.将文件放入类路径
Java应用程序的类路径通常包含以下位置:
- 项目的根目录
- /src/main/resources
- 任何位置的文件在项目构建后被复制到/classes文件夹中
如果文件位于JAR文件中,将JAR文件添加到项目的lib文件夹或将JAR文件添加到项目的类路径中。需要验证的重要一点是文件是否被复制到项目的最终构建输出中,即JAR文件、WAR文件或EAR文件中。
2.从类路径中读取文件
要在类中从类路径中读取文件,我们需要获取尝试读取文件的类的系统类加载器的引用。
系统类加载器显然知道应用程序的其他路径。一旦有了文件引用,就可以使用多种方法来读取文件。
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class ReadFileFromClasspath
{
public static void main(String[] args) throws Exception
{
//To avoid referring non-static method inside main() static method
ReadFileFromClasspath instance = new ReadFileFromClasspath();
File file = instance.getFile("demo.txt");
//validate file path
System.out.println(file.getPath());
//Read file
List<String> lines = Files.readAllLines(file.toPath());
System.out.println(lines);
}
private File getFile(String fileName) throws IOException
{
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(fileName);
if (resource == null) {
throw new IllegalArgumentException("file is not found!");
} else {
return new File(resource.getFile());
}
}
}
3.完整路径和相对路径
文件名可以以两种方式给出,即根目录路径和完整路径。
fileName.txt
– 在构建文件夹的根路径(例如/bin、/build、/WEB-INF/classes等)中搜索文件。com/howtodoinjava/io/demo.txt
– 表示构建目录中文件的完整路径。在这种情况下,实际文件位于位置<project_root>/bin/com/howtodoinjava/io/demo.txt。
如果对从类路径中读取文件有任何问题,请随时提出相关问题。