如何将文件读取到ArrayList后通过JOptionPane输出,解决Try/Catch语句报错问题
Catch语句常见报错原因
- 异常类型不匹配:文件读取操作会抛出
IOException,如果catch的是不相关的异常类型会直接编译报错,建议要么精准捕获FileNotFoundException+IOException,要么直接捕获父类Exception兜底 - 捕获顺序错误:同时捕获多个异常时必须把子类异常放在前面,父类异常放在后面,比如先写
catch(FileNotFoundException e)再写catch(IOException e),反过来父类异常把子类异常覆盖就会报错 - 语法错误:漏写异常变量名,比如写了
catch(IOException)没加变量e,正确写法是catch(IOException e)
完整实现代码示例
import javax.swing.JOptionPane; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class ReadFileToArrayList { public static void main(String[] args) { ArrayList<String> contentList = new ArrayList<>(); // 替换为你实际的文件路径 String file_path = "your_file_path.txt"; try (BufferedReader reader = new BufferedReader(new FileReader(file_path))) { String line; // 逐行读取文件内容写入ArrayList while ((line = reader.readLine()) != null) { contentList.add(line); } // 拼接ArrayList内容用于弹窗输出 StringBuilder output = new StringBuilder(); for (String text : contentList) { output.append(text).append("\n"); } JOptionPane.showMessageDialog(null, output.toString(), "文件读取结果", JOptionPane.INFORMATION_MESSAGE); } catch (IOException e) { // 异常捕获后弹窗提示错误 JOptionPane.showMessageDialog(null, "读取文件失败:" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE); // 控制台打印堆栈信息方便调试 e.printStackTrace(); } } }
注:以上代码基于Java 7+版本,用了try-with-resources语法会自动关闭IO流,不需要手动写finally逻辑。如果用更低版本Java,把流定义放在try块外,finally里手动关闭流即可。
内容的提问来源于stack exchange,提问作者Anh Le
相关产品推荐
相关产品推荐

