文本的倒序輸出
文件before:
Hello
World
要求輸出文件after:
World
Hello
代碼如下:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.ListIterator;
public class ReverseOrder extends ArrayList {
public static String read(String fileName) throws IOException {
StringBuffer sb = new StringBuffer();
LinkedList lines = new LinkedList();
BufferedReader in = new BufferedReader(new FileReader(fileName));
String s;
while ((s = in.readLine()) != null)
lines.add(s);
in.close();
ListIterator it = lines.listIterator(lines.size());
while (it.hasPrevious()) {
sb.append(it.previous());
sb.append("\n");
}
return sb.toString();
}
public static void write(String fileName, String text) throws IOException {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(
fileName)));
out.print(text);
out.close();
}
public ReverseOrder(String fileName) throws IOException {
super(Arrays.asList(read(fileName).split("\n")));
}
public void write(String fileName) throws IOException {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(
fileName)));
for (int i = 0; i < size(); i++)
out.println(get(i));
out.close();
}
public static void main(String[] args) throws Exception {
String fileName = "e:\\1124\\before.txt";
ReverseOrder text = new ReverseOrder(fileName);
text.write("e:\\1124\\after.txt");
}
/*
* 最后會(huì)多一個(gè)空行,手工刪除一下
*/
}
相關(guān)推薦:計(jì)算機(jī)等級(jí)考試二級(jí)Java編程的三十個(gè)基本規(guī)則北京 | 天津 | 上海 | 江蘇 | 山東 |
安徽 | 浙江 | 江西 | 福建 | 深圳 |
廣東 | 河北 | 湖南 | 廣西 | 河南 |
海南 | 湖北 | 四川 | 重慶 | 云南 |
貴州 | 西藏 | 新疆 | 陜西 | 山西 |
寧夏 | 甘肅 | 青海 | 遼寧 | 吉林 |
黑龍江 | 內(nèi)蒙古 |