[英]MemoryMapped File reading from a huge file separated by new line character
我正在使用內存映射的I / O讀取巨大的文件。 我遇到的問題是,我正在逐字符讀取MemoryMappedByteBuffer。 因此,我需要傳遞文件中存在的多個字符串,這些字符串之間用“ \\ n”分隔。
RandomAccessFile aFile = new RandomAccessFile(this.getFileName(), "r");
FileChannel inChannel = aFile.getChannel();
MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY,
0, inChannel.size());
buffer.load();
for (int i = 0; i < buffer.limit(); i++)
{ // There are many strings in the file separated by \n
System.out.println((char) buffer.get() == '\n'); // Gives true
//need to make a complete string over here.
}
buffer.clear(); // do something with the data and clear/compact it.
return null; // The String which has been made in the above for loop
這不是您要的答案,因為它不使用內存映射文件。 如果確實沒有幫助,我將其刪除。
我正在使用內存映射的I / O讀取巨大的文件
如果文件確實很大,那么您采用的方法將需要大量內存。
一種替代方法是使用BufferedReader
,這使您的任務變得微不足道:
final List<String> lines = new ArrayList<>();
final BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(file), charset));
String line;
while ((line = br.readLine()) != null)
{
lines.add(line);
}
return lines;
JDK實用程序方法Files.readAllLines(Path,Charset)
已經包含與該代碼等效的代碼:
讀取文件中的所有行。 此方法可確保在讀取所有字節或引發I / O錯誤或其他運行時異常時關閉文件。 使用指定的字符集將文件中的字節解碼為字符。
public static List<String> readAllLines(Path path, Charset cs) throws IOException
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.