不使用行分隔符的高效文本加载



所以我有一个相当大的(4mb)txt,其中包含单语词典的数据。因为单词的解释被分成多行,我无法逐行阅读。另一方面,我有可以使用的"###"分隔符。

我的问题是:在java/android中,将文本加载到地图中最有效的方法是什么?

将文件加载到单个String中,并对其使用split("###")方法。它为您提供了由分隔符分隔的字符串数组。4Mb可以立即将其加载到内存中。

byte[] encoded = Files.readAllBytes(Paths.get(filePath));
String fileContents = new String(encoded, encoding);
String[] lines = fileContents.split("###");

更新:不确定您是否可以使用该代码在android上读取文件-它适用于Java SE 7。在安卓系统上可以使用这样的代码:

FileInputStream fis;
fis = openFileInput(filePath);
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];
while ((n = fis.read(buffer)) != -1) 
{ 
  fileContent.append(new String(buffer, 0, n)); 
}
String[] lines = fileContent.toString().split("###");

最新更新