Java文件读写及对象排序

有一组学生对象信息,包括学生姓名、年龄,学号,现要求根据学生学号(String类型)对学生对象进行升序(降序)排序,并按指定大小写入到目标文件中。

[{"age":30,"name":"张三","number":"200906084130"}, {"age":24,"name":"李四","number":"200906084111"}, {"age":66,"name":"王五","number":"200906084166"}, {"age":34,"name":"赵六","number":"200906084132"}]

    

package com.wjl.study.fileiosort.rewrite;
/**
 * 学生对象类:实现Comparable接口
 */
public class Student implements Comparable<Student> {
    private String name;
    private int age;
    private String number;
    @Override
    public int compareTo(Student stu) {
        return number.compareTo(stu.number);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
}
package com.wjl.study.fileiosort.rewrite;

/**
 * java文件读写及对象排序
 */
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSON;

public class FileOption<T extends Comparable<T>> {
    /**
     * 读文件
     * 
     * @param readPath
     *            读文件路径
     * @param charSet
     *            设置编码
     * @param clazz
     *            待排序的Class
     * @return
     */
    @SuppressWarnings("unchecked")
    public T[] readFile(String readPath, String charSet, Class<T> clazz) {
        FileInputStream fis = null;
        InputStreamReader read = null;
        BufferedReader bf = null;
        try {
            List<T> bigList = new ArrayList<T>();
            // 1.首先获得文件句柄
            File file = new File(readPath);
            // 2.获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
            if (file.isFile() && file.exists()) {// 判断是否为文件及文件是否存在
                // 2.1 将文件内容读入到内存当中
                fis = new FileInputStream(file);
                // 2.2 InputStreamReader()这个方法进行解读刚才装进来内存当中的数据
                read = new InputStreamReader(fis, charSet);
                // 2.3 调用字节码读取的方法BufferedReader()转换成IO可以识别的数据
                bf = new BufferedReader(read);
                // 3 使用bufferedReader()的readline()方法一行一行读取txt文件中的数据。
                String line = null;
                while ((line = bf.readLine()) != null) {
                    System.out.println(line);
                    List<T> lineList = JSON.parseArray(line, clazz);
                    bigList.addAll(lineList);
                }
            } else {
                System.out.println("读取文件内容失败!");
            }
            return bigList.toArray((T[]) Array.newInstance(clazz, 0));
        } catch (Exception e) {
            System.out.println("读取文件内容出错!");
            e.printStackTrace();
            return null;
        } finally {
            if (bf != null) {
                try {
                    bf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (read != null) {
                try {
                    read.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 对文件对象进行排序
     * 
     * @param array
     * @param ase
     */
    public void sort(T[] array, final boolean ase) {
        T temp = null;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length - i - 1; j++) {
                if ((ase && (array[i].compareTo(array[j + 1])) > 0)
                        || (!ase && (array[i].compareTo(array[j + 1])) < 0)) {
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
    }
    /**
     * 写文件
     * 
     * @param savePath
     * @param num
     * @param array
     */
    public void writeFile(String savePath, int num, T[] array) {
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(savePath);
            bw = new BufferedWriter(fw);
            bw.write("[");
            for (int i = 0; i < array.length; i++) {
                bw.write(JSON.toJSONString(array[i]));
                if ((i + 1) % num == 0) {
                    bw.write("]\r\n");
                    if ((i + 1) < array.length) {
                        bw.write("[");
                    }
                } else if ((i + 1) < array.length) {
                    bw.write(",");
                } else if ((i + 1) == array.length) {
                    bw.write("]");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
package com.wjl.study.fileiosort.rewrite;
import java.util.Arrays;
public class TestMain {
    public static void main(String[] args) {
        String readPath = "D:\\myprogram\\array.txt";
        String savePath = "D:\\myprogram\\shortarray.txt";
        FileOption<Student> option = new FileOption<Student>();
        Student[] array = option.readFile(readPath, "GBK", Student.class);
        System.out.println(Arrays.toString(array));
        option.sort(array, true);
        System.out.println(Arrays.toString(array));
        option.writeFile(savePath, 2, array);
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值