![](/img/trans.png)
[英]Byte[] and java.lang.OutOfMemoryError reading file by bits
[英]reading file java.lang.OutOfMemoryError
试图在大文件中查找单词。 文件逐行读取。 读取redLine异常的方式时。 有什么办法解决吗? 您可以在地板上以字符串形式阅读它吗?
for(String line; (line = fileOut.readLine()) != null; ){
if(line.contains(commandString))
System.out.println(count + ": " + line);
count++;
}
java.lang.OutOfMemoryError:
UDP:
这是我所有的错误代码:
static String file = "files.txt";
static String commandString = "first";
static int count = 1;
public static void main(String[] args) throws IOException
{
try(BufferedReader fileOut = new BufferedReader(new InputStreamReader(new FileInputStream(file), "Cp1251")) ){
for(String line; (line = fileOut.readLine()) != null; ){
if(line.contains(commandString))
System.out.println(count + ": " + line);
count++;
}
System.out.println("before wr close :" + Runtime.getRuntime().freeMemory());
fileOut.close();
}catch(Exception e) {
System.out.println(e);
}
}
搜索一个单词,您可以按字节读取文件,而不必在内存中保留文件的单个字节以上。 逐字节读取,每次字节等于搜索到的单词的第一个字节,开始第二个循环并读取随后的字节,并检查下一个字节是否等于单词中的下一个字节,依此类推。 举一个例子,我已经根据您的需要修改了一个示例。
我省略了文件的输出,因为我不知道是要输出所有行还是仅输出包含关键字的行,而后者可能与逐行读取代码一样麻烦。
static String fileName = "files.txt";
static byte[] searchString = { 'f', 'i', 'r', 's', 't' };
static int count = 0;
static long position = 1;
public static void main(String[] args) throws IOException {
try (FileInputStream file = new FileInputStream(fileName)) {
byte read[] = new byte[1];
outerLoop: while (-1 < file.read(read, 0, 1)) {
position++;
if (read[0] == searchString[0]) {
int matches = 1;
for (int i = 1; i < searchString.length; i++) {
if (-1 > file.read(read, 0, 1)) {
break outerLoop;
}
position++;
if (read[0] == searchString[i]) {
matches++;
} else {
break;
}
}
if (matches == searchString.length) {
System.out.println((++count)+". found at position "+ (position-matches));
}
}
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.