gpt4 book ai didi

java - 有人能告诉我这个 Java 类是做什么的吗? I/O相关

转载 作者:行者123 更新时间:2023-12-01 19:23:33 24 4
gpt4 key购买 nike

我对 Java 比较陌生,正在尝试学习 I/O 语法。有人能给我大概介绍一下这段代码的作用吗?谢谢!!


导入java.io.*;



public class FileReader {
private String openFile="";
private String saveFile="";

FileReader(openFile, saveFile)
{
this.openFile=openFile;
this.saveFile=saveFile;
}



public String process(){
System.out.println(this.openFile);
System.out.println(this.saveFile);
BufferedReader open=null;
FileReader openFR=null;
FileWriter save=null;
int counter=0;

String output="";

if(openFile.equals("")){
return "No open file specifified\n";
}
if(this.saveFile.equals("")){
return "No save file specified\n";
}
try {
openFR = new FileReader(this.openFile);
open = new BufferedReader(openFR);

} catch (FileNotFoundException e) {
return ("Open file no longer exists\n");
}
try {
save = new FileWriter(saveFile);
}
catch (IOException e){
return ("Error saving the file\n");
}


try{
String temp = open.readLine();
while(temp != null){
temp = open.readLine();
counter++;
save.write(output + "\n");
}
} catch (IOException e){
e.getStackTrace();
return ("Error reading open file");
}

try {
save.flush();
} catch (IOException e) {
e.printStackTrace();
return ("Error writing save file");
}

return "Operation completed successfully";

}
}

最佳答案

这是一个很好的例子,说明了如何编码!

一些问题:

  • 不关闭流!
    这可能会由于锁定文件和/或不完整的写入文件而导致问题
  • 不使用异常或返回状态来指示错误。
    如果您想知道操作是否成功,则必须比较返回的字符串。如果有人更改了字符串,则相关应用程序将不再运行。
  • 仅在构造函数中设置的成员变量应该是final
    因此它们不会被意外分配。
  • 局部变量应在需要时声明
    在方法的开头声明它们是旧语言的遗留物
  • 不公开不明确的异常
    如果发生异常,您永远不会知道它是什么,您只会看到“读取打开文件时出错”

关于java - 有人能告诉我这个 Java 类是做什么的吗? I/O相关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2653277/

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