简体   繁体   中英

Java Exception Handling with Try in a method

I am trying to design two different methods for a Java application. 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. We're returning String and will declare 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 {
    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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