Java静态打印流错误

时间:2017-06-09 13:17:06

标签: java printstream

  

未报告的异常 java.io.FileNotFoundException ;一定是   抓住或宣布被抛出

我正在编写基本程序来生成脚本。我使用两种方法写入文件,因此,我认为我使用静态级别文件和打印流。

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

` 它不会跑,它要求我抓住或扔掉。我是否必须在类级别添加try-catch子句,这是否可能?

2 个答案:

答案 0 :(得分:3)

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");
}

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

{{1}}

答案 1 :(得分:0)

你不能像这样初始化PrintStream,因为它应该抛出异常所以你必须捕获这个异常,怎么样?您可以创建一个可以抛出此异常的方法,例如:

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();
    }
}