java - Java:定义为全局变量时处理 IOException
问题描述
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
尝试/捕捉:
try {
private static FileOutputStream fos = new FileOutputStream(fout);
} catch (IOException e) {
e.printStackTrace();
}
但是,当我执行这些方法时,我得到一个语法错误(Error:(8, 5) java: illegal start of type
)。我把代码放错地方了吗?
我该如何解决这个错误?
解决方案
使用静态块。(但是,将流声明为静态变量并不是一个好主意。资源管理要彻底。)
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();
}
}
推荐阅读
- javascript - 图像纵横比与新标签中的图像几乎没有区别
- node.js - Firebase Firestore 未显示在 nodejs 中创建的文档
- javascript - 请问有什么方法可以访问与 JavaScript 下拉列表中选择的值匹配的键吗?
- java - Java 可选 - 如何将一种类型的列表转换为另一种
- sass - 如何在检查元素中找到 scss 源地址文件?
- linux - 如何通过 bash 获取鼠标指针所在的窗口的 WID?
- postgresql - 在 postgres 日志文件中发现问题。太多“user=[unknown],db=[unknown],app=[unknown]”行
- django - 每次我尝试从 django admin 上传图像时,我都会收到此错误:“FOREIGN KEY 约束失败”
- python - 为什么“pip install”命令没有被 docker 缓存?
- markdown - 我可以使用 vuepress 和 vuepress-theme-hope 来做一些这样的事情吗?