0

How do I handle an IOException when the variable is a defined globally?
The error I get is Error:(8, 43) java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
This is my code:

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

    }
}

I am aware I can do throws IOException and try/catch like in this question :

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

but, when I do these methods I get a syntax error (Error:(8, 5) java: illegal start of type). Am I putting the code in the wrong place?
How do I solve this error?

joshkmartinez
  • 654
  • 1
  • 12
  • 35

1 Answers1

4

Use static blocks. (However, it is not a good idea to declare stream as a static variable. Be thorough about resource management.)

    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();
        }
    }
yeahseol
  • 377
  • 1
  • 6