请问finally关闭流时遇到Syntax error on token "finally", delete this token怎么办?

要做的例子是:一个文本文件,每一行都是0到100的整数,要查看每个数字在文件中出现的次数。

我的思路是先获取key为数字,value为次数的map,但是在方法里用finally关闭流遇到问题,

可是到finally这步总报错,下面代码

 

 

try
{
    fr=new FileReader(s);
} catch (FileNotFoundException e)
{
}
br=new BufferedReader(fr);
Map<Integer, Integer> map=new HashMap<Integer, Integer>();
String line=null;
for(int i=0;i<100;i++)//对所有行可能的数字进行迭代
{
    int num=0;
    try
    {
        while((line=br.readLine())!=null)//按行读缓冲区
        {
            if(Integer.parseInt(line)==i)
            {
                num++;
            }
        }       
    }
    catch(IOException e){/*处理异常*/}
    map.put(i, num);
}

finally //此处报错(Syntax error on token "finally", delete this token)
{
    try
    {
        if(br!=null)
            br.close();//关闭流
    } catch (IOException e)
    {
    }
}

 我google一下finally,说是只能跟在try或catch之后,可是要是碰到我这种状况怎么办呢?

 

你的逻辑有问题,for做了100次,然后while 读取br,会导致在第一次for迭代时就耗尽br,要么在for中打开br,要么br放到外面。

一个例子代码:
[code="java"]
{//java7
Map map=new HashMap<>();

try (BufferedReader br = new BufferedReader(new FileReader(""))) {
    for (String line; (line = br.readLine()) != null;) {
        String key = line.trim();
        Integer num = map.get(key);
        map.put(key, num == null ? 1 : num++);
    }
}

System.out.println("数字统计结果:" + map);

}

{//java6
Map map=new HashMap();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(""));
for (String line; (line = br.readLine()) != null;) {
String key = line.trim();
Integer num = map.get(key);
map.put(key, num == null ? 1 : num++);
}
} catch (IOException e) {
/** 异常处理 /
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
/
* 异常处理 */
}
}
}

System.out.println("数字统计结果:" + map);

}
[/code]

try
{
fr=new FileReader(s);
Map map=new HashMap();
String line=null;
for(int i=0;i<100;i++)//对所有行可能的数字进行迭代
{
int num=0;
while((line=br.readLine())!=null)//按行读缓冲区
{
if(Integer.parseInt(line)==i)
{
num++;
}
}

map.put(i, num);
}

} catch (Exception e1)
{
e1.printStackTrace();
}finally
{
try
{
if(br!=null)
br.close();//关闭流
} catch (IOException e)
{
}
}

finally 块必须与 try 或 try/catch 块配合使用。你想要关闭流就要在for循环中的catch代码块之后将这个finally代码块复制过去

你这是编译错误啊,finally的语法是这样的:

try{

} catch (Exception e){

} finally {

}

语法错误 改成如下即可
[code="java"]
try
{
fr=new FileReader(s);
br=new BufferedReader(fr);
Map map=new HashMap();
String line=null;
for(int i=0;i<100;i++)//对所有行可能的数字进行迭代
{
int num=0;
try
{
while((line=br.readLine())!=null)//按行读缓冲区
{
if(Integer.parseInt(line)==i)
{
num++;
}
}

}
catch(IOException e){/*处理异常*/}
map.put(i, num);
}

} catch (FileNotFoundException e)
{
}

finally //此处报错(Syntax error on token "finally", delete this token)
{
try
{
if(br!=null)
br.close();//关闭流
} catch (IOException e)
{
}
}[/code]