Java 在方法中使用 Try 进行异常处理

Java Exception Handling with Try in a method

我正在尝试为 Java 应用程序设计两种不同的方法。第一个方法会传入一个文件名的字符串,return一个文本文件的文本作为一个字符串。第二种方法会传入一个文件名和文本,并创建一个新的文本文件并将字符串输出到文件中。

目前我的代码在没有方法的情况下也能工作,但我正在尝试通过关注点分离和低耦合来设计它。我正在尝试修改它,这样我就可以调用一个方法来将字符串中的任何类型的数据输出到文本文件中。

这是我没有方法的代码:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class FileCopier {
    public static void main(String[] args) {
        //What file should be input for reading?
        String inputFile = askForInput("Please enter the name of the file to be read in: ");
        //What file should be created to display output ?
        String outputFile = askForInput("Please come up with a name of the file to be written backwards: ");
        //Check to make sure we got the names
        System.out.println("inputFile: " + inputFile + " outputFile: " + outputFile);
        // Variables to read and write the files

        //Call the readTextFile method to read text file into string data

        String line = null;
        String total = null;
        BufferedReader input = null;


        try {
            // FileReader reads text files in the default encoding.
            FileReader fileReader = new FileReader(inputFile);

            // Always wrap FileReader in BufferedReader.
            input = new BufferedReader(fileReader);

            total = input.readLine() + "\n";

            while ((line = input.readLine()) != null && total != null) {
                total += line + "\n";

                System.out.println("Proof that the file says: " + line);
            }

            input.close();

            //Check to make sure we got the text files data
            System.out.println("The total string says: \n" + total);
            //Call the reverseWords method to switch 'Hello' with 'World'
            String info = reverseWords(total);
            //Check to make sure the string was reversed
            System.out.println("The reversed string says: \n" + info);
            File file = new File(outputFile);
            BufferedWriter output = null;
            output = new BufferedWriter(new FileWriter(file));
            output.write(info);
            System.out.println("The output file: " + outputFile + " has been written.");
            output.close();

        } catch (FileNotFoundException ex) {
            System.out.println("Unable to open file '" +
                                       inputFile + "'");
        } catch (IOException ex) {
            System.out.println("Error reading file '" + inputFile + "'");
            // Or we could just do this: 
            // ex.printStackTrace();
        }
    }


    public static String reverseWords(String sentence) {
        String[] parts = sentence.trim().split("\s+");
        StringBuilder builder = new StringBuilder();
        builder.append(parts[parts.length - 1]);
        for (int i = parts.length - 2; i >= 0; --i) {
            builder.append(" ").append(parts[i]);
        }

        return builder.toString();
    }

    public static String askForInput(String question) {
        System.out.println(question);
        Scanner in = new Scanner(System.in);
        String inputFile = in.nextLine();
        return inputFile;
    }
}

在为我的代码的每个 "read" 和 "write" 部分创建方法时,我不断收到我认为来自异常处理的错误。关于如何分离涉及异常的代码有什么想法吗?

我不确定你在问什么,但尝试创建你自己的异常并让你的方法像这样抛出它们

package com.qmic.test;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class FileCopier {
    public static void main(String[] args) {

        // What file should be input for reading?
        String inputFile = askForInput("Please enter the name of the file to be read in: ");
        // What file should be created to display output ?
        String outputFile = askForInput("Please come up with a name of the file to be written backwards: ");
        // Check to make sure we got the names
        System.out.println("inputFile: " + inputFile + " outputFile: "
                + outputFile);
        // Variables to read and write the files

        // Call the readTextFile method to read text file into string data

        String line = null;
        String total = null;
        BufferedReader input = null;

        try {
            String readData = readFileContents(inputFile);
            // Check to make sure we got the text files data
            System.out.println("The total string says: \n" + readData);
            // Call the reverseWords method to switch 'Hello' with 'World'
            String reversedContents = reverseWords(readData);
            writeToFile(outputFile, reversedContents);
        } catch (ReadException ex) {
            System.out.println("Error reading file '" + inputFile + "'");
            // Or we could just do this:
            // ex.printStackTrace();
        } catch (WriteException ex) {
            System.out.println("Error Writing file '" + outputFile + "'");
            // Or we could just do this:
            // ex.printStackTrace();
        }

    }

    public static String reverseWords(String sentence) {
        String[] parts = sentence.trim().split("\s+");
        StringBuilder builder = new StringBuilder();
        builder.append(parts[parts.length - 1]);
        for (int i = parts.length - 2; i >= 0; --i) {
            builder.append(" ").append(parts[i]);
        }

        return builder.toString();
    }

    public static String askForInput(String question) {
        System.out.println(question);
        Scanner in = new Scanner(System.in);
        String inputFile = in.nextLine();
        return inputFile;

    }

    public static void writeToFile(String fileName, String data)
            throws WriteException {
        BufferedWriter output = null;
        try {
        // Check to make sure the string was reversed
        System.out.println("The reversed string says: \n" + data);
        File file = new File(fileName);

        output = new BufferedWriter(new FileWriter(file));
        output.write(data);
        System.out.println("The output file: " + fileName
                + " has been written.");

        }catch(IOException e){
            throw new WriteException();
        }finally{
            try {
                output.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    public static String readFileContents(String fileName) throws ReadException {
        // FileReader reads text files in the default encoding.
        BufferedReader input = null;
        String line = null;
        String total = null;

        try {
            FileReader fileReader = new FileReader(fileName);

            // Always wrap FileReader in BufferedReader.
            input = new BufferedReader(fileReader);

            total = input.readLine() + "\n";

            while ((line = input.readLine()) != null && total != null) {
                total += line + "\n";

                System.out.println("Proof that the file says: " + line);
            }

        } catch (IOException e) {
            throw new ReadException();
        }finally{
        //This is ugly code, if you are using java 7 you have extra option to better this
            try {
                input.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
        }
        return total;

    }

}
//make me public and move me to a separate file
class WriteException extends IOException {

}
//make me public and move me to a separate file
class ReadException extends IOException {

}

考虑单一职责。您需要执行两个不同的操作:读取和写入。

让我们从阅读开始吧。你现在正在做什么来阅读文件推测这些行:

// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputFile);

// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);

total = input.readLine() + "\n";

while ((line = input.readLine()) != null && total != null) {
    total += line + "\n";

    System.out.println("Proof that the file says: " + line);
}

input.close();

将其移至方法。

private static String readFile(String inputFile) throws IOException {
    BufferedReader input;
    String total;
    String line;// FileReader reads text files in the default encoding.
    FileReader fileReader = new FileReader(inputFile);

    // Always wrap FileReader in BufferedReader.
    input = new BufferedReader(fileReader);

    total = input.readLine() + "\n";

    while ((line = input.readLine()) != null) {
        total += line + "\n";

        System.out.println("Proof that the file says: " + line);
    }

    input.close();
    return total;
}

这是我们所做的:

  • 我们有一个变量 total 在程序的其他地方使用,因此必须保留其用法。我们要返回 String 并将在外面声明 total = readFile(inputFile);

  • 我们什么都没改变。此代码将 运行 与没有该方法的情况相同。

现在,如果我们要移动书写功能,那就是:

File file = new File(outputFile);
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(file));
output.write(info);
System.out.println("The output file: " + outputFile + " has been written.");
output.close();

...我们只是

private static void writeFile(String outputFile, String info) throws IOException {
    File file = new File(outputFile);
    BufferedWriter output = null;
    output = new BufferedWriter(new FileWriter(file));
    output.write(info);
    System.out.println("The output file: " + outputFile + " has been written.");
    output.close();
}

同样,此方法没有任何变化。这里的任何变量的其他用法我们都不用担心,所以我们可以直接把它传过来。

总而言之,try 块看起来有点贫血:

try {
    total = readFile(inputFile);
    //Check to make sure we got the text files data
    System.out.println("The total string says: \n" + total);
    //Call the reverseWords method to switch 'Hello' with 'World'
    String info = reverseWords(total);
    //Check to make sure the string was reversed
    System.out.println("The reversed string says: \n" + info);
    writeFile(outputFile, info);
} catch (FileNotFoundException ex) {
    System.out.println("Unable to open file '" +
                               inputFile + "'");
} catch (IOException ex) {
    System.out.println("Error reading file '" + inputFile + "'");
    // Or we could just do this:
    // ex.printStackTrace();
}

...这是一件 好事