我正在尝试编写一个处理读取文件的类。为了逐字阅读文件,我使用了以下在互联网上找到的代码。 Netbeans似乎不同意并说它无法在while循环中找到符号br。
public class Reader {
public String file2string() {
String line;
try (InputStream fis = new FileInputStream("smth")) {
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
} catch (IOException ex) {
Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
}
{
while ((line = br.readLine()) != null) {
String[] words = line.split(" ");
// Now you have a String array containing each word in the current line
}
}
return line;
}
}
答案 0 :(得分:1)
您的try语句后有{}
个阻止
{
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
}
然后你有另一个{}
阻止。
{
while ((line = br.readLine()) != null) {
String[] words = line.split(" ");
// Now you have a String array containing each word in the current line
}
}
第一个块中声明的变量在第二个块中不可见。
结合两个区块:
public String file2string() {
String line;
try (InputStream fis = new FileInputStream("smth")) {
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
String[] words = line.split(" ");
}
return line;
} catch (IOException ex) {
Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
}
// you need to decide what you want to return here if you got an exception.
}
您似乎正在拆分每一行并忽略结果,然后返回文件的最后一行。我不知道你为什么这样做,或者你真正想做的事情;但这是修复编译错误的方法。
答案 1 :(得分:1)
变量" br"在try {}块中声明,以便它的范围。它不会在那个街区之外可见。尝试将while循环放在try块中。
答案 2 :(得分:1)
您的循环超出了try
,因此变量br
在上下文中是未知的。将while-loop
放在try
结构中,如下所示:
public String file2string() {
String line = null;
try (InputStream fis = new FileInputStream("smth")) {
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
String[] words = line.split(" ");
// Now you have a String array containing each word in the current line
}
} catch (IOException ex) {
Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
}
return line;
}