【发布时间】:2016-01-12 15:41:18
【问题描述】:
我正在尝试编写一个程序,该程序给定一个包含五个或更多人的姓名和地址的文件,为每个人创建一个不同的文件(字母)(新文件将被命名为将接收的人它)。 主文件的结构是这样的:
type1.0001 #n John Harrison #a Whatever Street, 490 - Liverpool
.... and so on
所以“type1”是此人必须发送的信件类型,“#n”之后的单词是姓名,“#a”之后的单词是地址。
我一直在尝试的是:
String datos = "main_file.txt";
String tipo1 = "type1.txt";
String tipo2 = "type2.txt";
String tipo3 = "type3.txt";
char[] type1 = {'t', 'i', 'p', 'o', '1'};
//all other types should be here
String line;
FileReader fr = new FileReader("mainfile.txt");
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
while ((line = br.readLine()) != ".") {
char[] lineArray = line.toCharArray();
if (lineArray == type1) {
//code that creates file type1
}
}
}
fr.close();
到目前为止,这只是决定发送哪封信的代码,但它不起作用。 我认为这与“while”循环有关。
拜托,我 1 个月前开始使用 Java,如果有人能帮助我,我将不胜感激!
谢谢
现在,我有这个:
FileReader fr = new FileReader("main_file.txt");
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
String nameMark = "#n";
String addressMark = "#a";
int nameStart = line.indexOf(nameMark) + nameMark.length();
int addressStart = line.indexOf(addressMark) + addressMark.length();
String name = line.substring(nameStart, addressStart - addressMark.length());
String address = line.substring(addressStart, line.length());
if (line.startsWith("tipo1.")) {
FileWriter fw = new FileWriter("file1.txt");
char[] vector = name.toCharArray();
int index = 0;
while (index < vector.length) {
fw.write(vector[index]);
index++;
}
fw.close();
} else if (line.startsWith("tipo2.")) {
FileWriter fw = new FileWriter("file1.txt");
char[] vector = name.toCharArray();
int index = 0;
while (index < vector.length) {
fw.write(vector[index]);
index++;
}
fw.close();
}
}
fr.close();
但它不起作用。
谁能帮帮我?
【问题讨论】:
-
您有两个
readLine()调用,因此您在外部循环中获取一行,然后在第二个循环中获取另一行,丢弃第一行。所以你的外循环只会获取一行,它会被丢弃,然后内循环将处理文件的其余部分,外循环什么都没有。 -
感谢您的帮助!!现在我如何读取每个人的姓名和地址?我需要将它们都包含在每个新文件中
-
我编辑了我的问题,有人可以检查一下吗?