[問題] 文字資料排序
我有一筆通訊資料裡面記載 name, phone, email
只有 name 是必需的 phone 跟 email 可有可無
文字檔內容如下:
name pc mxn
phone 3246436
email pcmxn@mail.org
name fire ox
email fireox@isp.org
name kk mxn
phone 2135455
email kkmxn@mail.com
我想對這個文字檔作排序
e.g. 依 name 排序、或是依 phone 排序
目前只作了依 name 的排序
不過輸出的資料只有第一筆
應該是讀進來的資料在第一個迴圈就用掉了
所以第二、第三沒有資料可讀
不知道該怎麼寫才行
另外,如果想對 phone 或是 email 排序,該怎麼作呢
跟 name 的排序好像不太一樣
程式碼如下:
import java.util.*;
import java.io.*;
import java.lang.*;
public class Main {
public static void main(String[] args) throws Exception{
String inputfile = "input.txt";
String outputfile = "output.txt";
String[] person = new String[3];
FileReader input1 = new FileReader(inputfile);
Scanner content1 = new Scanner(input1);
String str;
int count = 0;
// 找出資料內的全部姓名並且存在 person 裡面
while (content1.hasNext()){
str = content1.next();
if (str.equals("name")){
person[count] = content1.next()+" "+content1.next();
count += 1;
}
}
// 將 person 排序
Arrays.sort(person);
String newLine = System.getProperties().getProperty("line.separator");
FileWriter output = new FileWriter(outputfile,true);
BufferedReader input = new BufferedReader(new FileReader(inputfile));
String line;
// 因為有三筆資料,所以將資料讀取三次
for (int i=0;i<3;i++){
input = new BufferedReader(new FileReader(inputfile));
Scanner content = new Scanner(input);
while (content.hasNextLine()){
line = content.nextLine();
if (line.indexOf(person[i])>=0){
// 如果該行有這個 name 就將該行寫入 output 直到讀到空白行
while (!line.trim().equals("")){
output.write(line + newLine);
line = content.nextLine();
}
}
}
}
input.close();
output.close();
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 125.225.166.232
推
05/19 17:09, , 1F
05/19 17:09, 1F
→
05/19 17:11, , 2F
05/19 17:11, 2F
→
05/19 17:11, , 3F
05/19 17:11, 3F
推
05/19 17:14, , 4F
05/19 17:14, 4F
推
05/19 19:36, , 5F
05/19 19:36, 5F
推
05/19 20:10, , 6F
05/19 20:10, 6F
→
05/19 20:34, , 7F
05/19 20:34, 7F
→
05/19 20:37, , 8F
05/19 20:37, 8F
推
05/22 17:02, , 9F
05/22 17:02, 9F