简体   繁体   English

如何从文本文件排序并写入另一个文本文件Java

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

I have this textfile which I like to sort based on HC from the pair HC and P3 我有这个文本文件,我想根据HC和P3对中的HC进行排序

This is my file to be sorted (avgGen.txt): 这是我要排序的文件(avgGen.txt):

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

Then my desired output into a new textfile (output.txt) is: 然后,我想要的输出到一个新的文本文件(output.txt)中是:

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

How can I sort the pairs HC and P3 from textfile where HC always appear for odd numbered index and P3 appear for even numbered index but I want the sorting to be ascending based on the HC value? 如何对文本文件中的HC和P3对进行排序,其中HC总是出现在奇数索引处,P3出现在偶数索引处,但是我希望根据HC值升序排序?

This is my code: 这是我的代码:

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();

  }
}

Please help. 请帮忙。

When you read from the input file, you essentially discarded the string values. 从输入文件读取时,实际上是丢弃了字符串值。 You need to retain those string values and associate them with their corresponding double values for your purpose. 您需要保留这些字符串值,并将它们与相应的双精度值关联以实现您的目的。

You can 您可以

  1. wrap the double value and the string value into a class, 将双精度值和字符串值包装到一个类中,
  2. create the list using that class instead of the double value alone 使用该类而不是仅使用double值创建列表
  3. Then sort the list based on the double value of the class using either a Comparator or make the class implement Comparable interface. 然后使用Comparator或使该类实现Comparable接口,根据该类的双精度值对列表进行排序。
  4. Print out both the double value and its associated string value, which are encapsulated within a class 打印封装在一个类中的double值及其关联的字符串值

Below is an example: 下面是一个示例:

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();
}

When your program reads lines from the input file, it splits each line, stores the double portion, and discards the rest. 当程序从输入文件中读取行时,它将拆分每一行,存储double部分,然后丢弃其余部分。 This is because only data[0] is used, while data[1] is not part of any expression. 这是因为仅使用data[0] ,而data[1]不是任何表达式的一部分。

There are several ways of fixing this. 有几种解决方法。 One is to create an array of objects that have the double value and the whole string: 一种是创建具有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;
    }
}

Create a list of objects of this class, sort them using a custom comparator or by implementing Comparable<StringWithSortKey> interface, and write out str members of sorted objects into the output file. 创建此类的对象列表, 使用自定义比较器或通过实现Comparable<StringWithSortKey>接口对它们进行排序 ,然后将已排序对象的str成员写到输出文件中。

Define a Pojo or bean representing an well defined/organized/structured data type in the file: 定义一个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);
    }

}

then after that: read->sort->store: 然后在那之后:读->排序->存储:

  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();

    }

Using , there is an easy way of performing this. 使用 ,有一种简单的方法可以执行此操作。

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);
}

Even better, using a Method reference 更好的是,使用方法参考

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('.'))));
}

By using double loop sort the items then just comapre it using the loop and right in the sorted order 通过使用双循环对项目进行排序,然后使用循环对它进行比较,并按排序顺序进行排序

     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