您好,我有一个工作程序,它读取 txt 文件(名称、ID、电子邮件、密码),并仅将名称和电子邮件写入 .html 扩展名的输出文件...
我的麻烦是我的程序在 1 个类下运行。但我的要求是我需要多个类.. 1 个用于处理,1 个用于阅读,1 个用于写入。您建议我如何分解我的文件?我有点困惑,感谢您的指导,谢谢
import java.io.*;
public class test {
public static void main(String[] args) throws Exception{
// define the path to your text file
System.out.println("Enter your file name \n");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String myFilePath = in.readLine();
String file1 = (myFilePath + ".txt");
System.setOut(new PrintStream(new FileOutputStream(myFilePath + ".html")));
// read and parse the file
try {
BufferedReader br = new BufferedReader(new FileReader(new File(file1)));
String line, name, email;
// read through the first two lines to get to the data
line = br.readLine();
line = br.readLine();
while ((line = br.readLine()) != null) {
if (line.contains("|")) {
// do line by line parsing here
line = line.trim();
// split the line
String[] parts = line.split("[|]");
// parse out the name and email
name = parts[1].trim();
email = parts[2].trim();
// rearrange the name
String[] nParts = name.split(" *");
if (nParts.length == 3) {
name = nParts[1] + " " + nParts[2] + " " + nParts[0];
} else {
name = nParts[1] + " " + nParts[0];
}
// all done now, let's print the name and email
System.out.println(email + " " + name);
}
}
br.close();
} catch (Exception e) {
System.out.println("There was an issue parsing the file.");
}
}
}
最佳答案
您正在寻找的是组件之间的逻辑分离。经验法则是:
"If tomorrow I write another program, will I be able to reuse some of this code?"
对于这种情况,请考虑程序中的不同部分:
处理文件 - 创建用于读/写文件的实用函数。直接写入输出流是一种设计思想,而不是重定向 System.out 和使用 System.out.println 写入(明天您可能想要写入多个输出流)。这也是处理错误的地方。
处理字符串数据 -
split
、trim
、concatenate
等。您可以编写一个接受字符串输入和根据要求输出一个新的处理后的String。 (明天的输入将来自网络而不是文件系统)。一个包含主函数的文件,该函数调用其他 2 个文件上的函数并包装进程。
关于java - 如何在Java中将1个文件程序分解为多个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22004050/