如何使用ArrayList对来自文本文件的项进行排序

时间:2014-05-02 01:23:51

标签: java arraylist

实际上我正在研究一个类来读取包含以下元素的文本文件:

Ringer-ID-0: USB\Device_Name_Here
Ringer-ID-0: {2344343r4efdwdd2w2sdwq}
Ringer-ID-0: volume =100;
Ringer-ID-0: speaker = off;
Ringer-ID-1: HDAUDIO\Device_Name_Here
Ringer-ID-1: {4r3444ewdwdaedw3re3d34d3}
Ringer-ID-1: volume = 93;
Ringer-ID-1: speaker = off;
Ringer-ID-2: HDAUDIO\Device_Name_Here
Ringer-ID-2: {23edecrrvt5y66h6hyyhy66}
Ringer-ID-2: volume = 93;
Ringer-ID-2: speaker = off;
Ringer-ID-3: HDAUDIO\Device_Name_Here
Ringer-ID-3: {3444444t56756y7h7h6ef}
Ringer-ID-3: volume = 93;
Ringer-ID-3: speaker = off;
Ringer-ID-4: USB\Device_Name_Here
Ringer-ID-4: {r4rfrf54g65g65g6h7uj7}
Ringer-ID-4: volume = 50;
Ringer-ID-4: speaker = on;

我需要对这些元素进行重新排列,以便让所有HDAUDIO设备的值都在我的列表顶部,而底部的USB设备就像这样:

Ringer-ID-0: HDAUDIO\Device_Name_Here
Ringer-ID-0: {4r3444ewdwdaedw3re3d34d3}
Ringer-ID-0: volume = 93;
Ringer-ID-0: speaker = off;
Ringer-ID-1: HDAUDIO\Device_Name_Here
Ringer-ID-1: {23edecrrvt5y66h6hyyhy66}
Ringer-ID-1: volume = 93;
Ringer-ID-1: speaker = off;
Ringer-ID-2: HDAUDIO\Device_Name_Here
Ringer-ID-2: {3444444t56756y7h7h6ef}
Ringer-ID-2: volume = 93;
Ringer-ID-2: speaker = off;
Ringer-ID-3: USB\Device_Name_Here
Ringer-ID-3: {2344343r4efdwdd2w2sdwq}
Ringer-ID-3: volume =100;
Ringer-ID-3: speaker = off;
Ringer-ID-4: USB\Device_Name_Here
Ringer-ID-4: {r4rfrf54g65g65g6h7uj7}
Ringer-ID-4: volume = 50;
Ringer-ID-4: speaker = on;

我认为首先将它们存储在数组列表中,但我不知道如何才能更好地实现这一目标,请提前帮助,先谢谢你们

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;



public class RearrangeItems {
    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(new File("C:\\Users\\John\\Desktop\\items.txt")));
            ArrayList<String> list = new ArrayList<String>();
            String line = reader.readLine();
            while (line != null) {
                list.add(line);
                line = reader.readLine();
            }
            reader.close();
            String[] records = (String[]) list.toArray(new String[] { "" });
            for (int i = 0; i < records.length; i++) {
                System.out.println(records[i]);
            }

        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您最好将信息读取到类中,然后将rearrage方法编写为此类类的集合。

public class RingerEntry {
    private int ringerID;
    private String ringerType; //USB | HDAUDIO
    private String ringerName; //device name
    private String hwID; // whatever is within { and }
    private int voluem;
    private boolean speakerStatus;
}

为此编写getter和setter。然后创建这些ArrayList并编写rearrange()函数以将列表作为参数并返回已排序的函数。您可以根据ringerType字段对列表中的元素进行简单排序。这会将您的所有HDAUDIO设备放在首位,USB设备将被推到最底层。

祝你好运!