[英]In Java, using the java.nio library and a FileChannel, how can I load a Properties object from a file?
在 Java 程序中,我得到了一個java.nio.Path
對象,我需要鎖定一個文件,然后從中加載一個java.util.Properties
對象。
我讀到獲取文件共享鎖的正確方法,表示為Path
,是獲取java.nio.channels.FileChannel
使用共享鎖channel.lock(0L, Long.MAX_VALUE, true)
鎖定它
final FileChannel channel = FileChannel.open(filePath, StandardOpenOption.READ);
final FileLock lock = channel.lock(0L, Long.MAX_VALUE, true);
現在我已經鎖定了頻道,我假設我現在應該在加載我的屬性文件時引用該頻道。
但是,我沒有看到將FileChannel
轉換為Properties
可讀的內容的簡單方法。 Properties
采用InputStream
或Reader
。 我可以實現我自己的閱讀器,但我確信我的團隊更願意使用開箱即用的東西(如果有的話)。
有沒有人知道這樣的事情?
我的基本假設不正確嗎? 如果是這樣,此過程的正確流程是什么?
您似乎錯過了Channels
助手類的存在:
Properties properties=new Properties();
try(final FileChannel channel = FileChannel.open(filePath, StandardOpenOption.READ);
final FileLock lock = channel.lock(0L, Long.MAX_VALUE, true)) {
properties.load(Channels.newInputStream(channel));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.