2

我正在创建一个类——只是一个类,没有 main() 并且我在这一行收到“未报告的异常 java.io.FileNotFoundException; 必须被捕获或声明为抛出”的错误:

FileOutputStream outStr = new FileOutputStream(FILE, true);   

我不明白; 我放入了一个 try{} catch{} 块,它仍在报告错误。

此外,它还报告了 try 和 both catch 行的“非法类型开始”,它还说 ';' 预计两条捕获线。

我正在使用 NetBean IDE,仅供参考。

感谢您的任何帮助。

这是完整的代码:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.FileNotFoundException;


public class UseLoggingOutputStream 
{

    String FILE = "c:\\system.txt";

    try
    {

        FileOutputStream outStr = new FileOutputStream(FILE, true);

    }

    catch(FileNotFoundException fnfe)
    {

        System.out.println(fnfe.getMessage());

    }

    catch(IOException ioe)
    {

        System.out.println(ioe.getMessage());

    }

}
4

5 回答 5

9

您需要将文件处理语句放在方法中:

import java.io.FileOutputStream;
import java.io.FileNotFoundException;

public class UseLoggingOutputStream {
    public void myMethod() {
        String file = "c:\\system.txt";
        try {
            FileOutputStream outStr = new FileOutputStream(file, true);
        } catch(FileNotFoundException fnfe) { 
            System.out.println(fnfe.getMessage());
        } 
    }
}
于 2011-04-21T19:24:51.917 回答
4

所有功能代码都需要进入方法 - 我在您的代码中没有看到方法 - 这是类型问题的非法开始。一旦掌握了基础知识,其他编译错误应该会变得更加清晰。

public class Foo {

  public void doSomething() {
    //code here 
  }

}
于 2011-04-21T19:17:18.300 回答
1

将此代码移至某个方法或至少移至静态初始化程序块。

于 2011-04-21T19:21:19.517 回答
1
import java.io.*;
import java.util.*; 

public class SortNames {

private String[] strings = new String[10];  

private int counter;

public SortNames() {

ArrayList<String> names = new ArrayList<String>();
Scanner scan = null;
File f = null;

try{
 f = new File("names.txt");
 scan = new Scanner(f);

  while(scan.hasNext()) names.add(scan.next());
}
  finally{scan.close();}

Collections.sort(names);

  for(String s:names) System.out.println(s);

     }  
} 
于 2011-11-18T18:29:35.270 回答
0

抱歉,如果这对您没有帮助,但我能够通过在包含 FileWriter 的方法调用中添加“ throws FileNotFoundException ”来解决这个确切的问题。我知道这可能没有帮助,因为您没有使用方法,但话又说回来,也许是。

于 2013-04-27T13:55:01.457 回答