【Java习作】KWIC模拟
作者:gnuhpc
出处:http://www.cnblogs.com/gnuhpc/
package org.bupt.kwic;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
public class mykwic {
private static BufferedReader input_file;
private ArrayList<String> kwicList;
public mykwic (String filename) //construct the index of file fname
{
kwicList = new ArrayList<String>();
String line="";
fileopen(filename);
while (line!= null)
{
line= readline();
if (line !=null)
{
parseLine(line, kwicList);
}
}
//Collections.sort(kwicList);
display ( kwicList );
}
public static void fileopen(String InputFilename) {
try {
input_file = new BufferedReader(new FileReader(InputFilename));
} catch (IOException e) {
System.err.println(("File not open" + e.toString()));
System.exit(1);
}
}
public static String readline() {
String line ="";
try {
line = input_file.readLine();
} catch (Exception e) {
e.getStackTrace();
}
return line;
}
public void parseLine(String line,ArrayList<String> list) {
StringTokenizer tokener = new StringTokenizer(line);
String token = new String();
int index;
ArrayList<String> tokens = new ArrayList<String>();
int count = tokener.countTokens();
for (int j = 0; j < count; j++) {//将一行解析,并且将解析的word加入ArrayList中
token = tokener.nextToken();
tokens.add(token);
}
//对ArrayList中的字进行循环移位,得出最后结果
for (int i = 0; i < count; i++) {
index=i;
StringBuffer linebuffer = new StringBuffer();
for (int j = 0; j < count; j++) {
if (index >= count)
index = 0;
linebuffer.append ( tokens.get(index) );
linebuffer.append (" ");
index++;
}
line = linebuffer.toString();
kwicList.add(line);
}
}
public static void display(ArrayList<String> List) {
System.out.println("Output is");
for (int count = 0; count < List.size(); count++) {
System.out.println (List.get (count) );
}
}
public static void main(String[] args) {
new mykwic("test.txt");
}
}