案例:为打乱顺序的出师表排序
Use Class:
BufferedReader、ArrayList、HashMap、Iterator、Properties、FileReader
以下为用到的文件,在网盘里面
链接:https://pan.baidu.com/s/1dUbNabdmH7RFstzUIPsnTA
提取码:6666
复制这段内容后打开百度网盘手机App,操作更方便哦–来自百度网盘超级会员V5的分享
public class chushibiao {
public static void main(String[] args) throws IOException {
// method_sort();
method_load();
}
// path -- E:\folder_io_dome\input_chushibiao.txt
public static void method_sort() throws IOException {
// create BufferedReader object
// 创建字符缓冲流
BufferedReader bufferedReader = new BufferedReader(new FileReader("E:\\folder_io_dome\\input_chushibiao.txt"));
String read_line_string = null;
// create ArrayList<String>
// 创建ArrayList集合
ArrayList<String> read_line_array = new ArrayList<>();
while (true) {
// get every line data
// 获取每行的数据
read_line_string = bufferedReader.readLine();
// save data
// 当本行数据不为空时,存入集合
if (read_line_string != null) read_line_array.add(read_line_string);
// end 当获取到的数据是null时,结束循环
if (read_line_string == null) break;
// output result
System.out.println(read_line_string);
}
// output array_list the length 输出集合的长度
System.out.println("Read_line_arr length is : " + read_line_array.size());
// 创建集合
HashMap<Integer, String> hashMap = new HashMap<>();
// save data
for (int i = 0; i < read_line_array.size(); i++) {
// will 'char number' to 'Integer number'
// 将字符数字转换为数字
Integer index = Integer.parseInt(read_line_array.get(i).charAt(0) + "");
// index为key string为value存入map集合中
hashMap.put(index, read_line_array.get(i).replace(read_line_array.get(i).charAt(0) + ".", ""));
}
// ergodic hashMap 遍历集合,并将数据存入properties
Properties properties = new Properties();
// 迭代器遍历
Iterator<Integer> iterator = hashMap.keySet().iterator();
while (iterator.hasNext()) {
Integer next = iterator.next();
// print index and value
System.out.println(next + "-> " + hashMap.get(next));
// save date on the properties
properties.setProperty(next + "", hashMap.get(next));
}
// create charOutputStream 创建字符输出流
FileWriter fileWriter = new FileWriter("E:\\folder_io_dome\\sort_chushibiao.txt");
// save disk 以固定格式保存到硬盘
properties.store(fileWriter, "sort after");
// 关闭流
fileWriter.close();
}
// load data and show data 加载数据,并显示数据
public static void method_load() throws IOException {
// create charInputStream 创建字符输入流
FileReader fileReader = new FileReader("E:\\folder_io_dome\\sort_chushibiao.txt");
Properties properties = new Properties();
// load data on the disk 自硬盘加载固定格式数据
properties.load(fileReader);
Iterator<String> iterator = properties.stringPropertyNames().iterator();
// ergodic data on the 'properties arr'
while (iterator.hasNext()){
String next = iterator.next();
System.out.println("Key is : " + next + " -> " + "Value is : " + properties.get(next));
}
// close stream
fileReader.close();
}
}