习题7:打开一个文本文件,每次读取一行内容。将每行作为一个String读入,并将那个String对象置入一个LinkedList中。按相反的顺序打印出LinkedList中的所有行。
/**
* @ClassName: BufferedInputFileDemo7
* @Description: 打开一个文本文件,每次读取一行内容。将每行作为一个String读入,并将那个String对象置入一个LinkedList中
* ,按相反的顺序打印出LinkedList中的所有行。
* @author CrazyCode
* @date 2012-4-22 下午06:33:57
*/
public class BufferedInputFileDemo7 {
/**
* @Title: read
* @Description: 根据文件名读取文件内容
* @authore CrazyCode
* @param filename
* @throws IOException
*/
private LinkedList<String> read(String filename) throws IOException {
return this.read(new File(filename));
}
/**
* @Title: read
* @Description: 根据文件读取文件内容
* @authore CrazyCode
* @param file
* @throws IOException
*/
private LinkedList<String> read(File file) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(file));
String s;
LinkedList<String> list = new LinkedList<String>();
while ((s = in.readLine()) != null) {
list.add(s);
}
return list;
}
/**
* @Title: print
* @Description: 默认正向打印方法
* @authore CrazyCode
* @param filename
* @throws IOException
*/
public void print(String filename) throws IOException {
this.print(new File(filename), false);
}
/**
* @Title: print
* @Description: 默认正向打印方法
* @authore CrazyCode
* @param file
* @throws IOException
*/
public void print(File file) throws IOException {
this.print(file, false);
}
/**
* @Title: print
* @Description: 可控的打印方法
* @authore CrazyCode
* @param filename
* @param isReverse
* @throws IOException
*/
public void print(String filename, boolean isReverse) throws IOException {
this.print(new File(filename), isReverse);
}
/**
* @Title: print
* @Description: 可控的打印方法
* @authore CrazyCode
* @param file
* @param isReverse
* @throws IOException
*/
public void print(File file, boolean isReverse) throws IOException {
LinkedList<String> list = this.read(file);
Iterator<String> iter = null;
if (isReverse) {
// descendingIterator()方法生成一个逆向的iterator
iter = list.descendingIterator();
} else {
iter = list.iterator();
}
// 遍历iterator 打印
while (iter.hasNext()) {
System.out.println(iter.next());
}
}
public static void main(String[] args) throws IOException {
BufferedInputFileDemo7 d7 = new BufferedInputFileDemo7();
d7.print("C:\\zerocms.sql");
}
}