抛出并捕获IOException

时间:2017-01-09 22:40:36

标签: java exception-handling io ioexception catch-block

   inputFileName = "2.txt";
   outputFileName = "3.txt";

   inputFile = new BufferedReader(new FileReader(inputFileName));
   outputFile = new PrintWriter(new FileWriter(outputFileName));

   String lineOfText = inputFile.readLine();

   while (lineOfText != null)
   {
       if (lineOfText.contains("x"))
       {
           lineOfText = lineOfText.replaceAll("x"+ ".*", "");
       } 
       outputFile.println(lineOfText);
       lineOfText = inputFile.readLine();
   } 

   inputFile.close();
   outputFile.close();

您好, 现在我有一个输入和输出,这是否意味着我有两个try和两个catch块(连接到前一个文件并写入第二个文件可能有错误)。或者我只需要一个试块?

如果是这样,我将如何/在哪里实现try和catch块?

2 个答案:

答案 0 :(得分:2)

我只能通过编写一个try / catch / finally-block来使用:

try {
    inputFile = new BufferedReader(new FileReader(inputFileName));
    outputFile = new PrintWriter(new FileWriter(outputFileName));
    String lineOfText = inputFile.readLine();
    while (lineOfText != null) {
        if (lineOfText.contains("x")) {
            lineOfText = lineOfText.replaceAll("x"+ ".*", "");
        } 
        outputFile.println(lineOfText);
        lineOfText = inputFile.readLine();
    } 
} catch(IOException ioe) {
        System.err.println("Caught IOException: " + ioe.getMessage());
} finally {
    if(inputFile != null)
        inputFile.close();
    if(outputFile != null)
        outputFile.close();
}

通过使用finally块,您可以确保ReaderWriter对象肯定已关闭。

答案 1 :(得分:2)

我建议使用{7}} Java 7块,如下例所示,它还将处理try with resources资源:

closing

Herepublic static void main(String[] args) throws Exception { String inputFileName = "2.txt"; String outputFileName = "3.txt"; try (BufferedReader inputFile = new BufferedReader(new FileReader(inputFileName)); PrintWriter outputFile = new PrintWriter(new FileWriter(outputFileName));) { String lineOfText = inputFile.readLine(); while (lineOfText != null) { if (lineOfText.contains("x")) { lineOfText = lineOfText.replaceAll("x" + ".*", ""); } outputFile.println(lineOfText); lineOfText = inputFile.readLine(); } }catch(Exception e){ //Handle } } 的文档。