Java:定义为全局变量时处理 IOException

标签 java global-variables

当变量是全局定义时,如何处理 IOException
我得到的错误是 Error:(8, 43) java: 未报告的异常 java.io.FileNotFoundException;必须被捕获或声明被抛出
这是我的代码:

import java.io.*;
public class generator {
    private static char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    private static StringBuilder partialSolution = new StringBuilder();
    private static File fout = new File("out.txt");
    private static FileOutputStream fos = new FileOutputStream(fout); //the syntax error is here
    private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

    private static void bt(int maxIndex, int index) throws IOException {

        if (index == maxIndex) {
            String solution = partialSolution.toString();
            System.out.println(solution);
            bw.write(solution);
            bw.newLine();
        } else {
            for (char c : alphabet) {
                partialSolution.append(c);
                bt(maxIndex, index + 1);
                final int lastCharIndex = partialSolution.length() - 1;
               partialSolution.deleteCharAt(lastCharIndex);
            }
        }
    }

    private static void btCaller(int maxIndex) throws IOException {
        bt(maxIndex, 0);
        bw.close();

    }

    public static void main(String[] args) throws IOException {
        btCaller(3);

    }
}

我知道我可以抛出IOException并尝试/捕获like in this question :

try {
    private static FileOutputStream fos = new FileOutputStream(fout);
} catch (IOException e) {
    e.printStackTrace();
}

但是,当我执行这些方法时,我收到语法错误(Error:(8, 5) java: invalid start of type)。我是否将代码放在错误的位置?
如何解决这个错误?

最佳答案

使用静态 block 。 (但是,将 Stream 声明为静态变量并不是一个好主意。要彻底进行资源管理。)

    private static char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    private static StringBuilder partialSolution = new StringBuilder();
    private static File fout = new File("out.txt");
    private static FileOutputStream fos;
    private static BufferedWriter bw;
    static {
        try {
            fos = new FileOutputStream(fout);
            bw = new BufferedWriter(new OutputStreamWriter(fos));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

关于Java:定义为全局变量时处理 IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54192814/

相关文章:

java - Android SimpleDateFormat 在午夜和凌晨 1 点之间返回不正确的时间

Python:未定义全局名称(但它不是全局变量)

php - 如何在 PHP 中存储变量以便在不同的脚本中使用?

MySQL 将全局变量应用于打开的 session

java - 使用局部变量来保存全局变量的目的是什么?

java - 安卓全局变量

java - Eclipse Java IDE JUnit5 : junit. jupiter.api.Assertions 无法访问

Java Spring - 动态生成的 csv 文件下载响应挂起

Java 一个 liner for 循环

java - 为什么 getConfiguration 偶尔会抛出 File不能为空?