如何从文本文件进行排序,并写入到另一个文本文件的Java

问题描述:

我有这个文本文件,我想基于来自对HC HC和排序P3如何从文本文件进行排序,并写入到另一个文本文件的Java

这是我要排序的文件(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出现偶数索引bu t我想根据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(); 

    } 
} 

请帮助。

当您从输入文件读取时,基本上放弃了字符串值。您需要保留这些字符串值并将它们与其相应的double值相关联以达到您的目的。

您可以

  1. 包裹双值和字符串值成一类,
  2. 使用,而不是double值类单独
  3. 然后进行排序基于双列表创建列表使用比较器的类的值或使类实现Comparable接口。
  4. 打印出两个双值及其相关联的字符串值,其被封装在一个类

下面内是一个例子:

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

我已经改变了我的期望输出,并且不知道如何根据HC和P3对而不是仅仅对它进行排序。我如何修复代码?谢谢 – Ina

当您的程序从输入文件中读取行时,它会拆分每行,存储double部分,并丢弃其余部分。这是因为只使用data[0],而不是任何表达式的一部分。

有几种方法可以解决这个问题。一个是创建具有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; 
    } 
} 

创建这个类,sort them using a custom comparator的对象或通过实现Comparable<StringWithSortKey>接口列表,排序的对象str成员写出来进入输出文件。

定义一个POJO或豆表示良好限定的/组织在文件/结构化数据类型:

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

通过采用双循环排序的项目 然后使用循环和右排定的顺序只是comapre它

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

      }