Maven get the file path resources, the document reads resources

File path after path problem all depends on the compiler

For example, the source file path is:

The file path is compiled:

In other words, file resources folder after compilation, is the root directory, in this case, for example, I want to read my.txt file path resources folder,

Written ①:

// After compilation, the project root path, wording. 1 
String = A. URL1 class .getClassLoader () the getResource ( "." ) .ToString ();
 // compiled project root path, writing 2 
String = URL2 A. class . the getResource ( "/" ) .toString ();
 // compiled, root file 
String = A. URL3 class .getResource ( "") toString ().;

Output:

file:/D:/IdeaWorkspace/test-null-project/target/classes/
file:/D:/IdeaWorkspace/test-null-project/target/classes/
file:/D:/IdeaWorkspace/test-null-project/target/classes/com/convict/

 

Written ②:

// There getFile method calls the latter getResource, there is no [file:], but in [/ D: xxx] the format 
String = A. URL4 class .getClassLoader () getResource ( "." ) .GetFile () ; 
String URL5 = A. class .getResource ( "/" ) .getFile (); 
String url6 = A. class .getResource ( "" ) .getFile (); 
System.out.println (URL4); 
System.out.println (URL5); 
System.out.println (url6);

Output:

/D:/IdeaWorkspace/test-null-project/target/classes/
/D:/IdeaWorkspace/test-null-project/target/classes/
/D:/IdeaWorkspace/test-null-project/target/classes/com/convict/

 

So far, there have been a variety of get on top of the file path way, since to get the path, you can read the file File, and then read the file, as this is the content of my.txt

The code reads the file contents may be as follows:

// 获取路径
String filePath = A.class.getClassLoader().getResource("my.txt").getFile();
File my = new File(filePath);
InputStreamReader isr = new InputStreamReader(new FileInputStream(my), StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
String lineTxt;
while ((lineTxt = br.readLine()) != null) {
    System.out.println(lineTxt);
}
br.close();

Output:

 

Guess you like

Origin www.cnblogs.com/convict/p/11330449.html