From: https://www.cnblogs.com/sunny3158/p/17818827.html
Java實現讀取resources目錄下的文件路徑通常有以下九種方式:
1. 使用ClassLoader的getResource()方法
在Java中,可以使用ClassLoader的getResource()方法獲取resources目錄下的文件路徑。示例代碼如下:
URL resource = getClass().getClassLoader().getResource("example.txt");
String path = resource.getPath();
System.out.println(path);
2. 使用ClassLoader的getResourceAsStream()方法
除了使用getResource()方法,還可以使用ClassLoader的getResourceAsStream()方法獲取資源流並讀取資源內容。示例代碼如下:
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("example.txt");
String content = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
System.out.println(content);
3. 使用ClassLoader的getSystemResource()方法
使用ClassLoader的getSystemResource()方法可以直接從系統路徑獲取資源,示例代碼如下:
URL resource = ClassLoader.getSystemResource("example.txt");
String path = resource == null ? "" : resource.getPath();
System.out.println(path);
4. 使用ClassLoader的getSystemResourceAsStream()方法
和第2種方式類似,ClassLoader的getSystemResourceAsStream()方法可以獲取資源流並讀取資源內容。示例代碼如下:
InputStream inputStream = ClassLoader.getSystemResourceAsStream("example.txt");
String content = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
System.out.println(content);
5. 使用ClassLoader的getResourceAsStream()方法結合Properties類讀取屬性文件
在Java中,可以使用Properties類讀取資源目錄下的屬性文件。示例代碼如下:
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("example.properties");
Properties properties = new Properties();
properties.load(inputStream);
String propertyValue = properties.getProperty("example.key");
System.out.println(propertyValue);
6. 使用java.io.FileInputStream讀取文件
除了使用ClassLoader,還可以使用java.io.FileInputStream讀取文件。示例代碼如下:
File file = new File("src/main/resources/example.txt");
FileInputStream fis = new FileInputStream(file);
byte[] fileContent = fis.readAllBytes();
String content = new String(fileContent, StandardCharsets.UTF_8);
System.out.println(content);
7. 使用java.nio.file.Path讀取文件
Java7中引入了java.nio.file.Path類,也可以使用該類讀取文件。示例代碼如下:
Path path = Paths.get(getClass().getClassLoader().getResource("example.txt").toURI());
byte[] fileContent = Files.readAllBytes(path);
String content = new String(fileContent, StandardCharsets.UTF_8);
System.out.println(content);
8. 使用spring的Resource類讀取文件
如果項目中使用了Spring框架,可以使用spring的Resource類讀取文件。示例代碼如下:
Resource resource = new ClassPathResource("example.txt");
InputStream inputStream = resource.getInputStream();
String content = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
System.out.println(content);
9. 使用Guava的Resources類讀取文件
Google開源的Guava庫中也提供了讀取資源文件的類Resources。示例代碼如下:
URL resource = Resources.getResource("example.txt");
String fileContent = Resources.toString(resource, StandardCharsets.UTF_8);
System.out.println(fileContent);
以上就是Java實現讀取resources目錄下的文件路徑的九種方式的完整攻略,希望對你有所幫助。
本站文章如無特殊說明,均爲本站原創,如若轉載,請註明出處:Java實現讀取resources目錄下的文件路徑的九種方式 - Python技術站
原文鏈接:https://pythonjishu.com/yupleomvlryqmxz/