抛出和捕获 IOException

Throwing and catching IOException

   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 块?

如果是这样,how/where 我会实施 try 和 catch 块吗?

我只会使用一个 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 对象确实已关闭。

我建议使用 try with resources 块 Java 7,如下例所示,它也会处理 closing 资源:

public 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
    }
}

Heretry with resources 的文档。