日期:2014-05-20 浏览次数:20738 次
import java.io.*; import java.util.*; public class ReadFile { private static final String[] types = new String[] //存储关键字 { "Directed by", "Produced by", "Written by", "Starring", "Music by", "Cinematography", "Editing by", "Studio", "Distributed by", "Release date(s)", "Running time", "Country", "Language", "Budget" }; private ArrayList<FileStruct> fileStructs = new ArrayList<FileStruct>(); //存储数据 public ReadFile(String filename) throws IOException { BufferedReader in = new BufferedReader(new FileReader(filename)); String str = null; while ((str = in.readLine()) != null) { if (isType(str)) //是关键字的话,就添加新的FileStruct { fileStructs.add(new FileStruct(str)); } else if (! str.equals("") && fileStructs.size() != 0) { FileStruct fileStruct = fileStructs.get(fileStructs.size() - 1); fileStruct.add(str); //在最后的FileStruct中添加信息 } } in.close(); } /** * 打印信息 */ public void printInfos() { for (FileStruct fileStruct : fileStructs) { System.out.println(fileStruct.type); for (int i = 0; i < fileStruct.list.size(); i++) { System.out.println("(" + (i + 1) + ") " + fileStruct.list.get(i)); } System.out.println(); } } /** * 判断是否是关键字 * @param str * @return */ private boolean isType(String str) { for (int i = 0 ; i< types.length; i++) { if (types[i].equals(str)) { return true; } } return false; } public static void main(String[] args) throws IOException { ReadFile readFile = new ReadFile("1.txt"); readFile.printInfos(); } } class FileStruct { public String type; public ArrayList<String> list; public FileStruct(String type) { this.type = type; list = new ArrayList<String>(); } public void add(String str) { list.add(str); } }