簡體   English   中英

使用Try方法的Java異常處理

[英]Java Exception Handling with Try in a method

我正在嘗試為Java應用程序設計兩種不同的方法。 第一種方法將傳入文件名的字符串,並以字符串形式返回文本文件的文本。 第二種方法將傳入文件名和文本,並創建一個新的文本文件並將字符串輸出到文件中。

目前,我的代碼在沒有這些方法的情況下可以工作,但是我正在嘗試以關注點分離和低耦合的方式設計它。 我正在嘗試對其進行修改,因此我只能調用一種方法來將字符串中的所有數據輸出到文本文件。

這是我的沒有方法的代碼:

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

當為我的代碼的每個“讀”和“寫”部分創建一個方法時,我不斷地從錯誤處理中得到錯誤。 關於如何分離涉及異常的代碼有什么想法?

我不確定您在問什么,但嘗試創建自己的異常並讓您的方法像這樣拋出它們

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

......這是一件好事

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM