1 JAVA.IO位元組流

inputstream.png"/>
21.png"/>
resource.png
- ResourceLoader是為了屏蔽了Resource的具體實作,統一資源的獲取方式,你即能從ResourceLoader加載ClassPathResource,也能加載FileSystemResource等
public interface ResourceLoader {
// 默認從類路徑加載的資源 前綴: "classpath:",獲取ClassPathResource
String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;
Resource getResource(String location);
- ResourceLoader介面默認對classpath路徑下面的資源進行加載
public interface ResourcePatternResolver extends ResourceLoader {
// 默認加載所有路徑(包括jar包)下面的檔案,"classpath*:", 獲取ClassPathResource
String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
- ResourcePatternResolver默認會加載所有路徑下面的檔案,獲得ClassPathResource;classpath:只會在class類路徑下查找;而classpath*:會掃描所有JAR包及class類路徑下出現的檔案
//Ant風格運算式 com/smart/**/*.xml
ResourcePatternResoler resolver = new PathMatchingResourcePatternResolver();
Resource resources[] = resolver.getResources("com/smart/**/*.xml");
// ApplicationContext ctx
//FileSystemResource資源
Resource template = ctx.getResource("file:///res.txt");
//UrlResource資源
Resource template = ctx.getResource("https://my.cn/res.txt");
- ResourceLoader方法getResource的locationPattern可設定資源模式前綴來獲取非ClassPathResource資源,locationPattern支持Ant風格
前綴 示例 描述 classpath: classpath:config.xml 從類路徑加載 file: file:///res.txt 從檔案系統加載FileSystemResource http: http://my.cn/res.txt 加載UrlResource
9 JAVA.Properties了解一下
- Properties是java自帶的配置處理類;Properties加載資源的兩種方式
public class Properties extends Hashtable<Object,Object>{
.... //可根據Reader或者InputStream加載properties檔案內容
public synchronized void load(Reader reader) throws IOException
public synchronized void load(InputStream inStream) throws IOException
- Properties讀取配置示例代碼
//res.properties
username = root
password = password
-------代碼示例-------------
InputStream input = ClassLoader.getSystemResourceAsStream("res.properties");
Properties prop = new Properties();
prop.load(inputStream); //根據inputStream載入資源
String username = prop.getProperty("username");
10 yml配置資源的讀取
- 普通java專案如果需要讀取yml可引入jackson-dataformat-yaml,而springboot默認配置支持yml的讀取
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.9.5</version>
- 基于jackson-dataformat-yaml對yml配置資源的讀取
//res.yml 配置
name: chen
params:
url: http://www.my.com
----------代碼示例---------------
InputStream input = ClassLoader.getSystemResourceAsStream("res.yml");
Yaml yml = new Yaml();
Map map = new Yaml().loadAs(input, LinkedHashMap.class);; //根據inputStream載入資源
String name = MapUtils.getString(map,"name"); // chen
//url: http://www.my.com
11 優雅地關閉資源,try-with-resource語法和lombok@Cleanup
- 資源的打開就需要對應的關閉,但我們常會忘記關閉資源,或在多處代碼關閉資源感到雜亂,有沒有簡潔的關閉方法呢?
- 自動關閉資源類需實作AutoCloseable介面和配合try-with-resource語法糖使用
public class YSOAPConnection implements AutoCloseable {
private SOAPConnection connection;
public static YSOAPConnection open(SOAPConnectionFactory soapConnectionFactory) throws SOAPException {
YSOAPConnection ySoapConnection = new YSOAPConnection();
SOAPConnection connection = soapConnectionFactory.createConnection();
ySoapConnection.setConnection(connection);
return ySoapConnection;
}
public SOAPMessage call(SOAPMessage request, Object to) throws SOAPException {
return connection.call(request, to);
}
@Override
public void close() throws SOAPException {
if (connection != null) { connection.close(); }
}
}
//自動關閉的資源類使用示例
try (YSOAPConnection soapConnection=YSOAPConnection.open(soapConnectionFactory)){
SOAPMessage soapResponse = soapConnection.call(request, endpoint);
...//資料操作
} catch (Exception e) {
log.error(e.getMessage(), e);
...
}
- lombok注解@Cleanup,物件生命周期結束時會呼叫public void close();物件需實作AutoCloseable介面
import lombok.Cleanup;
@Cleanup // @Cleanup的使用
YSOAPConnection soapConnection=YSOAPConnection.open(soapConnectionFactory)
12 資源不關閉,會導致什么最壞的結果
- JDK的原生資源類不關閉,它也不會永遠存在,JVM會借助finalize自動關閉它,例如FileInputStream
//FileInputStream.java - JDK8
//jdk8的FileInputStream重寫了finalize,保證物件回收前開啟的資源被關閉
protected void finalize () throws IOException {
if (guard != null) {
guard.warnIfOpen();
}
if ((fd != null) && (fd != FileDescriptor.in)) {
close();
}
}
- 在JDK9后,用Cleaner機制代替了finalize機制;Cleaner機制自動回收的物件同樣需要實作AutoCloseable介面;Cleaner是基于PhantomReference實作的;對實作細節感興趣的同學,可自行查閱下相關檔案
- 但是使用JDK的提供的資源關倍訓制的,那么資源的關閉比手動關閉時要延后很長時間的,據測驗,使用try-with-resources關閉資源,并讓垃圾回收器回收它的時間在12納秒,而使用finalizer機制,時間增加到550納秒
- 不及時關閉資源,就會占用資源,影響其他執行緒的執行;比如linux的檔案資源,linux行程默認能打開的最大檔案數是1024(有的是2048,此數值是可配置的);如果一個執行緒持有十幾個檔案資源,還要等550納秒用finalizer機制釋放資源,同行程的其他執行緒都等到花謝了
作者:clswcl
鏈接:https://juejin.im/post/6856266775022174222
來源:掘金
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/208917.html
標籤:其他
