gpt4 book ai didi

Java 异常处理与方法中的 Try

转载 作者:太空宇宙 更新时间:2023-11-04 13:47:36 26 4
gpt4 key购买 nike

我正在尝试为 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;
}
}

当为代码的每个“读取”和“写入”部分创建方法时,我不断收到错误,我认为这些错误来自异常处理。关于如何分离涉及异常的代码有什么想法吗?

最佳答案

从单一责任的角度思考。您需要执行两个不同的操作:读取和写入。

让我们从阅读开始吧。您现在正在执行的读取文件的操作推测了这些行:

// 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 block 看起来有点贫乏:

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

...这是一件好事

关于Java 异常处理与方法中的 Try,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30675126/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com