当前位置:网站首页>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 !

边栏推荐
- 七月集训(第15天) —— 深度优先搜索
- The lifecycle of arkui development framework components
- 【树莓派】Box相关手册-4 Web代理
- Read the paper learning to measure changes: full revolutionary Siamese metric networks for scene change detect
- [leetcode -- the first day of introduction to programming ability] basic data type [statistics of odd numbers within the range / average wage after removing the minimum wage and maximum wage)
- Qt中发送信号时参数为结构体或者自定义的类怎么办?
- 6S parameters
- NPM install error forced installation
- pollFirst(),pollLast(),peekFirst(),peekLast()
- 2068. Check whether the two strings are almost equal
猜你喜欢

Hard core structure, violent interpretation
![[C language _ review _ learn Lesson 2] what is base system? How to convert between hexadecimals](/img/ef/b7a9214e69150c069e352af758f614.png)
[C language _ review _ learn Lesson 2] what is base system? How to convert between hexadecimals

pollFirst(),pollLast(),peekFirst(),peekLast()

Sentry 2 orbital data download

快应用自定义进度条

JS call and apply

HBuilder 微信小程序中运行uni-app项目

【微信小程序】农历公历互相转换

NCCL (NVIDIA Collective Communications Library)

C language takes you to tear up the address book
随机推荐
ESP8266-Arduino编程实例-ADC
Read the paper snunet CD: a densely connected Siamese network for change detection of VHR images
七月集训(第03天) —— 排序
Community attribute of BGP
[C language _ review _ learn Lesson 2] what is base system? How to convert between hexadecimals
ES6 new symbol data type
【CTF】ciscn_2019_es_2
Antdesign a-modal自定义指令实现拖拽放大缩小
BGP的社团属性
[C language - zero foundation lesson 9] love and hate in functions
Nut weather
STL container -- Application of set set
How to register code cloud account
Analog library function
The lifecycle of arkui development framework components
全排列递归思路整理
Transpose and inverse of [linear algebra 01] matrix
MySQL transaction
ES6 new - string part
基于ArkUI eTS开发的坚果笑话(NutJoke)