简体   繁体   English

使用Try方法的Java异常处理

[英]Java Exception Handling with Try in a method

I am trying to design two different methods for a Java application. 我正在尝试为Java应用程序设计两种不同的方法。 The first method will pass in a string of the name of a file, and return the text of a text file as a string. 第一种方法将传入文件名的字符串,并以字符串形式返回文本文件的文本。 The second method will pass in the name of a file and the text, and create a new text file and output the string into the file. 第二种方法将传入文件名和文本,并创建一个新的文本文件并将字符串输出到文件中。

Currently my code works without the methods, but I am trying to design it with a separation of concerns and low coupling. 目前,我的代码在没有这些方法的情况下可以工作,但是我正在尝试以关注点分离和低耦合的方式设计它。 I am trying to modify it so I can just call a method to output any sort of data I have in a string to a text file. 我正在尝试对其进行修改,因此我只能调用一种方法来将字符串中的所有数据输出到文本文件。

Here is my code without the methods: 这是我的没有方法的代码:

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

When creating a method for each of the "read" and "write" portions of my code, I constantly get errors that I assume are from the exception handling. 当为我的代码的每个“读”和“写”部分创建一个方法时,我不断地从错误处理中得到错误。 Any thoughts on how to separate code that has exceptions involved? 关于如何分离涉及异常的代码有什么想法?

I am not sure what are you asking about but try to create your own Exceptions and make your methods throw them like this 我不确定您在问什么,但尝试创建自己的异常并让您的方法像这样抛出它们

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 {

}

Think in terms of single responsibility. 考虑单一责任。 You have two distinct operations that need to happen: reading and writing. 您需要执行两个不同的操作:读取和写入。

Let's start with reading. 让我们从阅读开始。 What you're doing right now to read the file surmises these lines: 您现在正在读取文件的操作推测出以下几行:

// 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();

Move that to a method. 将其移至方法。

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

Here's what we did: 这是我们所做的:

  • We have a variable total which is used elsewhere in the program, so that usage has to be preserved. 我们有一个可变的total ,可以在程序的其他地方使用,因此必须保留使用情况。 We're returning String and will declare total = readFile(inputFile); 我们返回String ,并声明total = readFile(inputFile); on the outside. 在外面。

  • We've changed nothing. 我们什么都没改变。 This code will run the same way as it did without the method. 该代码将以与没有该方法的方式相同的方式运行。

Now, if we want to move the writing functionality, which is: 现在,如果我们要移动书写功能,那就是:

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();

...we just do . ...我们只是

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();
}

Again, nothing's changed on this method. 同样,此方法没有任何变化。 We don't have any other usages of any of the variables in here to worry about, so we can directly bring it across. 在这里,我们不需要担心任何其他变量的用法,因此我们可以直接使用它。

All said, that try block looks a bit anemic: 所有人都说, 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();
}

...which is a good thing. ......这是一件好事

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM