[英]Memory map directly to string
我有一個文件,我正在通過“FileChannel.map()”映射到 memory。 但是,在讀取字符串以執行以下操作時似乎有點奇怪:
1) read a int for the string length
2) allocate a byte[length] object
3) use .get to read length bytes
4) convert the byte[] to a string
現在我從我的 C++ 背景中知道,memory 映射文件作為指向 memory 的指針提供給用戶。 那么有沒有一種很好的方法可以跳過使用字節數組,只在映射的 memory 之后進行字符串轉換 go?
最終,沒有。 但是有一種方法可以將數據視為字符。 查看 ByteBuffer.asCharBuffer()。
在內部, asCharBuffer() 方法執行您提議的相同操作,但以逐個字符為基礎。
我建議:
MappedByteBuffer mapped = fileChannel.map(mode, position, size);
String s = new String(mapped.array());
也可以使用 mapped.asCharBuffer() 並通過這種方式獲取字符。
沒有繞過 String 想要數據的私有副本。 字符串是不可變的,如果它使用共享數組,你可以打破它。 不幸的是,沒有String(CharSequence)
或String(ByteBuffer)
構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.