簡體   English   中英

在 Java 中,使用 java.nio 庫和 FileChannel,如何從文件加載 Properties 對象?

[英]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采用InputStreamReader 我可以實現我自己的閱讀器,但我確信我的團隊更願意使用開箱即用的東西(如果有的話)。

有沒有人知道這樣的事情?

我的基本假設不正確嗎? 如果是這樣,此過程的正確流程是什么?

您似乎錯過了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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM