并提前感谢您的帮助。我是Java新手,没有任何正式的Java教育。我正在制作一个Minecraft Bukkit服务器进行练习,并在创建时将标记位置记录到文件中。我试图创建一个布尔值,如果该位置已经在文件中,则返回true,如果不是,则返回false。我不能使用while循环,否则它冻结服务器,所以我使用for循环。无论如何,BufferedReader返回的所有行都是null,我不知道为什么。我有一个整数,使用BufferedReader返回文件中的行数,工作正常。我不明白它为什么用布尔值返回null。这是布尔值:
代码块:
private boolean isDuplicate(String in) throws IOException
{
File f = file;
try {
fr = new FileReader(f);
br = new BufferedReader(fr);
} catch (FileNotFoundException e1) {
log(Level.WARNING, "File not found.");
}
String temp;
in = in.substring(0,in.length() - 1);
for(int i = 0; i < (countLines(f)); i++)
{
if((temp = br.readLine()) != null)
{
String s = temp;
log(temp);
}
}
return false;
}
这是整数:
private int countLines(File f){
try {
fr = new FileReader(f);
br = new BufferedReader(fr);
} catch (FileNotFoundException e1) {
log(Level.WARNING, "File not found!");
}
for(int i = 0; i < 100000; i++)
{
try
{
if(br.readLine() == null)
{
return i;
}
}
catch (NullPointerException e)
{
return i;
}
catch (IOException e)
{
}
}
return 0;
}
答案 0 :(得分:2)
明显的原因&#39;是你已到达文件的末尾。但这段代码是无稽之谈。你根本不需要提前计算的行数,你肯定不需要在循环中每次都计算它们,这就是你当前的代码所做的。目前您的处理是 O(N 2 ),这是灾难性的。只需致电readLine()
,直到它返回null:
while ((line = br.readLine()) != null)
{
// ...
log(line);
}
注意:isDuplicate()
方法无法做任何与其名称略有相似的内容。
答案 1 :(得分:1)
该代码存在相当多的问题(最明显的是:当你捕获'FileNotFound'时,你应该返回并记录'致命' - 继续没有意义)。 我还假设您的实际代码不是您显示的代码(它不会编译)。
无论如何,这是你用Java读取文件的方式:
public boolean isDuplicate(String lookup, String filename) {
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
int lineNo = 0;
while ((line = reader.readLine()) != null) {
lineNo++;
// best would be to use a regex to match against the line
// however, the naive approach would be
if (line.indexOf(lookup) != -1) {
log.info(String.format"Lookup term %s found on line %d", lookup, lineNo);
return true;
}
}
log.info(String.format("Lookup term %s not found in %s", lookup, filename);
return false;
} catch (IOException e) {
// log a fatal error and bail
log.error(String.format("Could not read from %s [%s]", filename, e.getLocalizedMessage()));
// here best practice would be to throw your own custom application ex
throw new MyApplicationException(e);
}
}
while
和for
的行为基本相同;你while
永远“没有”返回“的原因可能是由于你在countlines()
方法中”耗尽“了这段资源。
答案 2 :(得分:0)
首先,您不需要countLines函数或使用它的for循环。您可以用
替换if语句while((temp = br.readLine()) != null)
其次,countLines正在使用全局bufferedReader并且可能已经读完整个文件。任何新的br.readLine()都将从此返回null。因此,当您从countlines函数返回并尝试执行br.readLine()时,您将获得一个空值。