我希望我的程序能够读取/搜索.dat文件中的多个代码*(例如:与240-667-XXXX具有相同6位数的电话号码)*我想将这些代码打印到新的.dat文件。我似乎陷入困境,当我试图寻找帮助我的东西时,我似乎无法工作。如果你能提供帮助,我将不胜感激。谢谢。
import java.io.*;
import java.util.*;
import java.io.PrintWriter;
public static void main(String[] args) throws IOException {
try {
BufferedReader readFile = new BufferedReader(
new FileReader("file_1.dat"));
System.out.println("entry to file: success");
int count = 0;
while (true) {
String line = reader.readLine();
if (line == null){
break;
}
System.out.println(line);
}
BufferedWriter write = new BufferedWriter(new PrintWriter("file_2.dat"));
} catch (FileNotFoundException e) {
System.out.println("Error1");
}
}
Update_1:我取出了Scanner,更改了while循环,将OubjectOutputStream更改为BufferedWriter,并添加了if语句。但我仍然需要帮助让程序在具有不同目的的电话号码中搜索重复的号码(240-667-XXXX)。
答案 0 :(得分:0)
我不确定您要阅读哪个文件,'file_1.dat'或'inrecords.dat'。我将假设它的'file_1.dat'。那么你的代码应该是这样的:
public static void main(String[] args) {
BufferedReader readFile = null;
try {
readFile = new BufferedReader(new FileReader(new File(
"file_1.dat")));
System.out.println("entry to file: success");
String line;
while ((line=readFile.readLine()) != null) {
if (line.contains("240-667-"))
System.out.println("the line:" + line);
}
} catch (IOException ex) {
ex.printStackTrace();
}finally {
try {
if (readFile != null)readFile.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
查看BufferedReader的java文档:http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html
答案 1 :(得分:0)
1)您使用BufferedReader打开文件,但是您没有从中读取任何内容。为什么?
2)使用ObjectOutputStream打开文件,但不要在其中写入任何内容。为什么? 首先,ObjectOutputStream不是编写字符串的最佳选择。 更好地使用BufferedWriter (http://docs.oracle.com/javase/7/docs/api/index.html?java/io/BufferedWriter.html) 如果要写入另一个文件,则应在此类中使用write方法。 因此,在迭代之前创建BufferedWriter,并在循环中使用write方法写入第二个文件。
编辑: 还有一件事。尝试将所有代码放在一个try {}块中。这是一种最佳实践。