簡體   English   中英

如何從文本文件排序並寫入另一個文本文件Java

[英]How to sort from text file and write into another text file Java

我有這個文本文件,我想根據HC和P3對中的HC進行排序

這是我要排序的文件(avgGen.txt):

7686.88,HC
20169.22,P3
7820.86,HC
19686.34,P3
6805.62,HC
17933.10,P3

然后,我想要的輸出到一個新的文本文件(output.txt)中是:

 6805.62,HC
17933.10,P3  
7686.88,HC
20169.22,P3  
7820.86,HC
19686.34,P3

如何對文本文件中的HC和P3對進行排序,其中HC總是出現在奇數索引處,P3出現在偶數索引處,但是我希望根據HC值升序排序?

這是我的代碼:

public class SortTest {
 public static void main (String[] args) throws IOException{
    ArrayList<Double> rows = new ArrayList<Double>();
    ArrayList<String> convertString = new ArrayList<String>(); 
    BufferedReader reader = new BufferedReader(new FileReader("avgGen.txt"));

    String s;
    while((s = reader.readLine())!=null){
        String[] data = s.split(",");
        double avg = Double.parseDouble(data[0]);
        rows.add(avg);
    }

    Collections.sort(rows);

    for (Double toStr : rows){
        convertString.add(String.valueOf(toStr));
    }

    FileWriter writer = new FileWriter("output.txt");
    for(String cur: convertString)
        writer.write(cur +"\n");

    reader.close();
    writer.close();

  }
}

請幫忙。

從輸入文件讀取時,實際上是丟棄了字符串值。 您需要保留這些字符串值,並將它們與相應的雙精度值關聯以實現您的目的。

您可以

  1. 將雙精度值和字符串值包裝到一個類中,
  2. 使用該類而不是僅使用double值創建列表
  3. 然后使用Comparator或使該類實現Comparable接口,根據該類的雙精度值對列表進行排序。
  4. 打印封裝在一個類中的double值及其關聯的字符串值

下面是一個示例:

static class Item {
    String str;
    Double value;

    public Item(String str, Double value) {
        this.str = str;
        this.value = value;
    }
}
public static void main (String[] args) throws IOException {
    ArrayList<Item> rows = new ArrayList<Item>();
    BufferedReader reader = new BufferedReader(new FileReader("avgGen.txt"));

    String s;
    while((s = reader.readLine())!=null){
        String[] data = s.split(",");
        double avg = Double.parseDouble(data[0]);
        rows.add(new Item(data[1], avg));
    }

    Collections.sort(rows, new Comparator<Item>() {

        public int compare(Item o1, Item o2) {
            if (o1.value < o2.value) {
                return -1;
            } else if (o1.value > o2.value) {
                return 1;
            }
            return 0;
        }
    });

    FileWriter writer = new FileWriter("output.txt");
    for(Item cur: rows)
        writer.write(cur.value + "," +  cur.str + "\n");

    reader.close();
    writer.close();
}

當程序從輸入文件中讀取行時,它將拆分每一行,存儲double部分,然后丟棄其余部分。 這是因為僅使用data[0] ,而data[1]不是任何表達式的一部分。

有幾種解決方法。 一種是創建具有double值和整個字符串的對象數組:

class StringWithSortKey {
    public final double key;
    public final String str;
    public StringWithSortKey(String s) {
        String[] data = s.split(",");
        key = Double.parseDouble(data[0]);
        str = s;
    }
}

創建此類的對象列表, 使用自定義比較器或通過實現Comparable<StringWithSortKey>接口對它們進行排序 ,然后將已排序對象的str成員寫到輸出文件中。

定義一個Pojo或bean,代表文件中定義良好/組織良好的數據類型:

class Pojo implements Comparable<Pojo> {
    private double value;
    private String name;

    @Override
    public String toString() {
    return "Pojo [value=" + value + ", name=" + name + "]";
    }

    public double getValue() {
    return value;
    }

    public void setValue(double value) {
    this.value = value;
    }

    public String getName() {
    return name;
    }

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

    /**
     * @param value
     * @param name
     */
    public Pojo(double value, String name) {
    this.value = value;
    this.name = name;
    }

    @Override
    public int compareTo(Pojo o) {

    return ((Double) this.value).compareTo(o.value);
    }

}

然后在那之后:讀->排序->存儲:

  public static void main(String[] args) throws IOException {
    List<Pojo> pojoList = new ArrayList<>();
    BufferedReader reader = new BufferedReader(new FileReader("chat.txt"));

    String s;
    String[] data;
    while ((s = reader.readLine()) != null) {
        data = s.split(",");
        pojoList.add(new Pojo(Double.parseDouble(data[0]), data[1]));
    }

    Collections.sort(pojoList);

    FileWriter writer = new FileWriter("output.txt");
    for (Pojo cur : pojoList)
        writer.write(cur.toString() + "\n");

    reader.close();
    writer.close();

    }

使用 ,有一種簡單的方法可以執行此操作。

public static void main(String[] args) throws IOException {
    List<String> lines =
    Files.lines(Paths.get("D:\\avgGen.txt"))
         .sorted((a, b) -> Integer.compare(Integer.parseInt(a.substring(0,a.indexOf('.'))), Integer.parseInt(b.substring(0,b.indexOf('.')))))
         .collect(Collectors.toList());

    Files.write(Paths.get("D:\\newFile.txt"), lines);
}

更好的是,使用方法參考

public static void main(String[] args) throws IOException {
    Files.write(Paths.get("D:\\newFile.txt"), 
                Files.lines(Paths.get("D:\\avgGen.txt"))
                     .sorted(Test::compareTheStrings)
                     .collect(Collectors.toList()));
}

public static int compareTheStrings(String a, String b) {
    return Integer.compare(Integer.parseInt(a.substring(0,a.indexOf('.'))), Integer.parseInt(b.substring(0,b.indexOf('.'))));
}

通過使用雙循環對項目進行排序,然后使用循環對它進行比較,並按排序順序進行排序

     public static void main(String[] args) throws IOException {
                ArrayList<Double> rows = new ArrayList<Double>();
                ArrayList<String> convertString = new ArrayList<String>(); 
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new FileReader("C:/Temp/AvgGen.txt"));
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                String s;
            try {
                while((s = reader.readLine())!=null){
                    String[] data = s.split(",");
                    convertString.add(s);
                    double avg = Double.parseDouble(data[0]);
                    rows.add(avg);
                }
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            FileWriter writer = new FileWriter("C:/Temp/output.txt");;
            Collections.sort(rows);
                 for (double sorted : rows) {
                     for (String value : convertString) {
                     if(Double.parseDouble(value.split(",")[0])==sorted)
                     {

                         writer.write(value +"\n");
                     }
                }

            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM