代码之家  ›  专栏  ›  技术社区  ›  joshkmartinez

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

  •  0
  • joshkmartinez  · 技术社区  · 6 年前

    我怎么处理 IOException 当变量是全局定义的?
    我得到的错误是 Error:(8, 43) java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
    这是我的代码:

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

    我知道我能做到 throws IOException 尝试/捕捉 like in this question :

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

    但是,当我执行这些方法时,我会得到一个语法错误( Error:(8, 5) java: illegal start of type )我把代码放错地方了吗?
    如何解决此错误?

    1 回复  |  直到 6 年前
        1
  •  3
  •   yeahseol    6 年前

    使用静态块。(但是,将流声明为静态变量不是一个好主意。深入了解资源管理。)

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