2017-06-09 34 views
-1

未报告的异常java.io.FileNotFoundException;必须是 被捕或宣称被抛出Java静态PrintStream的错误

我在写一个基本的程序来生成一个脚本。我使用两种方法来写文件,所以,我想我的用户静态级文件和printstream.`

static String fileName = "R1"; 
static File inputFile = new File(fileName+".txt"); 
static PrintStream write = new PrintStream(fileName+"_script.txt"); 

` 它将无法运行,它要求我赶上或抛。我是否需要在课堂级别添加try-catch子句,甚至可能吗?

+1

您可以初始化的变量中包含一个try/catch静态初始化器块。 – khelwood

回答

3

PrintStream构造函数抛出一个需要捕捉的异常,但是如果你只是做了,你就无法处理;

static PrintStream write = new PrintStream(fileName + "_script.txt"); 

所以你的选择是:

尝试定义静态块

static String fileName = "R1"; 
static File inputFile = new File(fileName + ".txt"); 
static { 
    try { 
     PrintStream write = new PrintStream(fileName + "_script.txt"); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
} 

,甚至更好地定义一个静态方法来初始化这些对象:

static String fileName; 
static File inputFile; 
static PrintStream write; 

public static void init() throws FileNotFoundException { 
    fileName = "R1"; 
    inputFile = new File(fileName + ".txt"); 
    write = new PrintStream(fileName + "_script.txt"); 
} 
+0

看起来这些静态变量可能永远不会改变,在这种情况下,它们应该被声明为final。但是如果你使用'init()',你不能让它们最终。 –

+0

@KlitosKyriacou我们必须问OP,如果这背后的想法是使用那些作为常量..那么你是正确的,那些必须是最终的....感谢您的反馈! –

+1

我认为在你的第一个选项中,'write'应该被声明为一个静态字段,而不是静态块中的局部变量。否则,没有意义。 – khelwood

0

你可以用” t像这样初始化PrintStream,因为它应该抛出一个异常,所以你必须c atch这个例外,怎么样?您可以创建可抛出该异常的方法。例如:

static String fileName; 
static File inputFile; 
static PrintStream write; 

public static void init() throws FileNotFoundException { 
//------------------^^-------^^ 
    fileName = "R1"; 
    inputFile = new File(fileName + ".txt"); 
    write = new PrintStream(fileName + "_script.txt"); 
} 

甚至可以赶上你的异常有:

public static void init() { 
    fileName = "R1"; 
    inputFile = new File(fileName + ".txt"); 
    try { 
     write = new PrintStream(fileName + "_script.txt"); 
    } catch (FileNotFoundException ex) { 
     ex.printStackTrace(); 
    } 
}