当前位置:网站首页>Nine ways to read the file path under the resources directory
Nine ways to read the file path under the resources directory
2022-07-27 09:29:00 【Java confidant_】
Click on the official account , Practical technical articles Know in time 
Antecedents feed
This article provides nine ways to obtain resources How to file in the directory . The method of printing documents is as follows :
/**
* Read the contents of the file according to the file path
*
* @param fileInPath
* @throws IOException
*/
public static void getFileContent(Object fileInPath) throws IOException {
BufferedReader br = null;
if (fileInPath == null) {
return;
}
if (fileInPath instanceof String) {
br = new BufferedReader(new FileReader(new File((String) fileInPath)));
} else if (fileInPath instanceof InputStream) {
br = new BufferedReader(new InputStreamReader((InputStream) fileInPath));
}
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}Mode one
The main core method is to use getResource and getPath Method , there getResource("") There is an empty string
public void function1(String fileName) throws IOException {
String path = this.getClass().getClassLoader().getResource("").getPath();// Be careful getResource("") There is an empty string
System.out.println(path);
String filePath = path + fileName;
System.out.println(filePath);
getFileContent(filePath);
}Mode two
The main core method is to use getResource and getPath Method , Directly through getResource(fileName) Method to get the file path , Note that if there is Chinese in the path, you must use URLDecoder.decode decode .
/**
* Directly through the file name getPath To get the path
*
* @param fileName
* @throws IOException
*/
public void function2(String fileName) throws IOException {
String path = this.getClass().getClassLoader().getResource(fileName).getPath();// Be careful getResource("") There is an empty string
System.out.println(path);
String filePath = URLDecoder.decode(path, "UTF-8");// If there is Chinese in the path, it will be URLEncoder, So here we need to decode
System.out.println(filePath);
getFileContent(filePath);
}Mode three
Directly through file name +getFile() To get the files . If it's a file path getFile and getPath The effect is the same , If it is URL In terms of path getPath Is a path with parameters .
As shown below :
url.getFile()=/pub/files/foobar.txt?id=123456
url.getPath()=/pub/files/foobar.txt Use getFile() The code to obtain the file is as follows :
/**
* Directly through the file name +getFile() To get
*
* @param fileName
* @throws IOException
*/
public void function3(String fileName) throws IOException {
String path = this.getClass().getClassLoader().getResource(fileName).getFile();// Be careful getResource("") There is an empty string
System.out.println(path);
String filePath = URLDecoder.decode(path, "UTF-8");// If there is Chinese in the path, it will be URLEncoder, So here we need to decode
System.out.println(filePath);
getFileContent(filePath);
}Mode 4 ( important )
Use it directly getResourceAsStream Method get stream , The above methods all need to get the file path , But in SpringBoot All the files in the are in jar In bag , There is no actual path , Therefore, the following methods can be used .
/**
* Use it directly getResourceAsStream Method get stream
* springboot This method needs to be used in the project , because jar There is no actual path in the package to store files
*
* @param fileName
* @throws IOException
*/
public void function4(String fileName) throws IOException {
InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);
getFileContent(in);
}Methods five ( important )
Mainly used getResourceAsStream Method get stream , Don't use getClassLoader have access to getResourceAsStream("/ Configuration testing .txt") Directly from resources Get from the root path ,SpringBoot All the files in the are in jar In bag , There is no actual path , Therefore, the following methods can be used .
/**
* Use it directly getResourceAsStream Method get stream
* If not used getClassLoader, have access to getResourceAsStream("/ Configuration testing .txt") Directly from resources Get from the root path
*
* @param fileName
* @throws IOException
*/
public void function5(String fileName) throws IOException {
InputStream in = this.getClass().getResourceAsStream("/" + fileName);
getFileContent(in);
}Mode 6 ( important )
adopt ClassPathResource Class to get the file stream ,SpringBoot All the files in the are in jar In bag , There is no actual path , Therefore, the following methods can be used .
/**
* adopt ClassPathResource Class gets , Suggest SpringBoot Use in
* springboot This method needs to be used in the project , because jar There is no actual path in the package to store files
*
* @param fileName
* @throws IOException
*/
public void function6(String fileName) throws IOException {
ClassPathResource classPathResource = new ClassPathResource(fileName);
InputStream inputStream = classPathResource.getInputStream();
getFileContent(inputStream);
}Mode 7
Get the location of files in the project through the absolute path , Only the local absolute path , Cannot be used for server acquisition .
/**
* Get the location of files in the project through the absolute path ( Cannot be used for server )
* @param fileName
* @throws IOException
*/
public void function7(String fileName) throws IOException {
String rootPath = System.getProperty("user.dir");//E:\WorkSpace\Git\spring-framework-learning-example
String filePath = rootPath + "\\chapter-2-springmvc-quickstart\\src\\main\\resources\\"+fileName;
getFileContent(filePath);
}Mode 8
adopt new File("") Get the current absolute path , Only the local absolute path , Cannot be used for server acquisition .
/**
* Get the location of files in the project through the absolute path ( Cannot be used for server )
* @param fileName
* @throws IOException
*/
public void function8(String fileName) throws IOException {
// The parameter is empty.
File directory = new File("");
// Canonical path :getCanonicalPath() Method returns the absolute path , Will be able to ..\ 、.\ Such symbols are resolved
String rootCanonicalPath = directory.getCanonicalPath();
// Absolute path :getAbsolutePath() Method returns the absolute path of the file , If it is a full path when constructing, it will directly return to the full path , If the construction is a relative path , Return the path of the current directory + structure File Object
String rootAbsolutePath =directory.getAbsolutePath();
System.out.println(rootCanonicalPath);
System.out.println(rootAbsolutePath);
String filePath = rootCanonicalPath + "\\chapter-2-springmvc-quickstart\\src\\main\\resources\\"+fileName;
getFileContent(filePath);
}Mode 9
Mainly by setting environment variables , Put the file in the environment variable , The principle is also obtained through absolute path .
In the example, I set an environment variable :TEST_ROOT=E:\\WorkSpace\\Git\\spring-framework-learning-example
System.getenv("TEST_ROOT");
System.getProperty("TEST_ROOT")By setting environment variables , Then get the file through the absolute path
/**
* Get the location of files in the project through the absolute path
*
* @param fileName
* @throws IOException
*/
public void function9(String fileName) throws IOException {
System.setProperty("TEST_ROOT","E:\\WorkSpace\\Git\\spring-framework-learning-example");
// The parameter is empty.
String rootPath = System.getProperty("TEST_ROOT");
System.out.println(rootPath);
String filePath = rootPath + "\\chapter-2-springmvc-quickstart\\src\\main\\resources\\"+fileName;
getFileContent(filePath);
}source :blog.csdn.net/u011047968/article/details/107311462
recommend
Technical involution group , Learn together !!

PS: Because the official account platform changed the push rules. , If you don't want to miss the content , Remember to click after reading “ Looking at ”, Add one “ Star standard ”, In this way, each new article push will appear in your subscription list for the first time . spot “ Looking at ” Support us !

边栏推荐
- The whole process of principle, simulation and verification of breath lamp controlled by FPGA keys
- 1344. 时钟指针的夹角
- [C language - zero foundation _ study _ review _ lesson 4] data types and operations
- ArcGIS pro2.8 deep learning environment configuration based on rtx30 graphics card
- BGP联邦实验
- Summary of traversal methods
- Ztree custom title attribute
- Special exercises for beginners of C language to learn code for the first time
- [C language - zero foundation lesson 10] adventure of array Kingdom
- 【云原生】我怎么会和这个数据库杠上了?
猜你喜欢

基于 FPGA 按键控制呼吸灯原理、仿真及验证全过程

Hard core structure, violent interpretation

NCCL (NVIDIA Collective Communications Library)

ES6 new symbol data type

Nacos做注册中心使用
![[micro service ~sentinel] sentinel dashboard control panel](/img/df/2fbe7826ea2b80a81d29351052ae28.png)
[micro service ~sentinel] sentinel dashboard control panel

500 error reporting

Special exercises for beginners of C language to learn code for the first time

NCCL 集合通信--Collective Operations

HBuilder 微信小程序中运行uni-app项目
随机推荐
七月集训(第09天) —— 二分查找
2022软件测试面试题 200道大厂面试真题 刷完拿到10k职位
Qt中发送信号时参数为结构体或者自定义的类怎么办?
Read the paper learning to measure changes: full revolutionary Siamese metric networks for scene change detect
Explanation of common basic controls for C # form application (suitable for Mengxin)
2068. Check whether the two strings are almost equal
IDL MODIS generate lookup table
函数防抖节流
七月集训(第14天) —— 栈
Nutrecipes developed based on arkui ETS
面试官:什么是脚手架?为什么需要脚手架?常用的脚手架有哪些?
[cloud native kubernetes practice] deploy the rainbow platform under the kubernetes cluster
七月集训(第17天) —— 广度优先搜索
七月集训(第21天) —— 堆(优先队列)
Programming style
You haven't heard of such 6 question brushing websites, have you? Are you out?
【树莓派】Box相关手册-4 Web代理
工程材料期末考试试卷
6S parameters
Music experience ceiling! Emotional design details of 14 Netease cloud music