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块?
答案 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
块,您可以确保Reader
和Writer
对象肯定已关闭。
答案 1 :(得分:2)
我建议使用{7}} Java 7块,如下例所示,它还将处理try with resources
资源:
closing
Here是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
}
}
的文档。