【问题标题】:Java static printstream error [duplicate]Java静态打印流错误[重复]
【发布时间】:2017-06-09 13:17:06
【问题描述】:

未报告的异常java.io.FileNotFoundException;一定是 被抓到或被宣布扔掉

我正在编写一个基本程序来生成一个脚本。我正在使用两种方法写入文件,所以,我想我会使用静态级别文件和打印流。`

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

` 它不会跑,它要求我接球或扔球。我是否必须在类级别添加一个 try-catch 子句,这甚至可能吗?

【问题讨论】:

  • 您可以在包含 try/catch 的静态初始化程序块中初始化您的变量。

标签: java printstream


【解决方案1】:

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

【讨论】:

  • 看起来这些静态变量可能永远不会改变,在这种情况下,它们应该被声明为final。但是如果你使用init(),你就不能让它们成为最终的。
  • @KlitosKyriacou 我们必须询问 OP 背后的想法是否将它们用作常量。那么你是对的,那些必须是最终的......谢谢您的反馈!!
  • 我认为在您的第一个选项中write 应该被声明为静态字段而不是静态块内的局部变量。否则没有意义。
【解决方案2】:

你不能像这样初始化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();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 2011-09-04
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多