如何从文本文件排序并写入另一个Java文本文件
我有这个文本文件,我喜欢根据HC和P3对HC进行排序 这是我要排序的文件(avgGen.txt): 然后,我希望在新文本文件(output.txt)中的输出是: 如何从textfile中对HC和P3进行排序,其中HC始终显示为奇数索引,P3显示为偶数索引,但我希望排序基于HC值升序 这是我的代码:如何从文本文件排序并写入另一个Java文本文件,java,sorting,text-files,java-8,Java,Sorting,Text Files,Java 8,我有这个文本文件,我喜欢根据HC和P3对HC进行排序 这是我要排序的文件(avgGen.txt): 然后,我希望在新文本文件(output.txt)中的输出是: 如何从textfile中对HC和P3进行排序,其中HC始终显示为奇数索引,P3显示为偶数索引,但我希望排序基于HC值升序 这是我的代码: public class SortTest { public static void main (String[] args) throws IOException{ ArrayList&l
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();
}
}
公共类排序测试{
公共静态void main(字符串[]args)引发IOException{
ArrayList行=新的ArrayList();
ArrayList convertString=新的ArrayList();
BufferedReader=new BufferedReader(新文件阅读器(“avgGen.txt”);
字符串s;
而((s=reader.readLine())!=null){
字符串[]数据=s.split(“,”);
double avg=double.parseDouble(数据[0]);
行。添加(平均值);
}
集合。排序(行);
用于(双toStr:行){
convertString.add(String.valueOf(toStr));
}
FileWriter=newfilewriter(“output.txt”);
for(字符串cur:convertString)
writer.write(cur+“\n”);
reader.close();
writer.close();
}
}
请提供帮助。当您的程序从输入文件中读取行时,它会分割每一行,存储
双倍部分,并丢弃其余部分。这是因为只使用了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;
}
}
创建此类对象的列表,或通过实现接口,并将排序对象的成员写入输出文件。从输入文件读取时,基本上丢弃了字符串值。您需要保留这些字符串值,并将它们与相应的双精度值关联起来
你可以
将双精度值和字符串值包装到一个类中
使用该类而不是仅使用双精度值创建列表
然后使用比较器或使类实现可比较接口,根据类的双值对列表进行排序
打印出封装在类中的双精度值及其关联的字符串值
以下是一个例子:
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();
}
静态类项{
字符串str;
双重价值;
公共项(字符串str,双值){
this.str=str;
这个值=值;
}
}
公共静态void main(字符串[]args)引发IOException{
ArrayList行=新的ArrayList();
BufferedReader=new BufferedReader(新文件阅读器(“avgGen.txt”);
字符串s;
而((s=reader.readLine())!=null){
字符串[]数据=s.split(“,”);
double avg=double.parseDouble(数据[0]);
添加(新项目(数据[1],平均值));
}
Collections.sort(行,新比较器(){
公共整数比较(项目o1、项目o2){
如果(o1.值o2.值){
返回1;
}
返回0;
}
});
FileWriter=newfilewriter(“output.txt”);
用于(当前项目:行)
writer.write(cur.value+“,“+cur.str+”\n”);
reader.close();
writer.close();
}
定义一个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);
}
}
类Pojo实现了可比较的{
私人双重价值;
私有字符串名称;
@凌驾
公共字符串toString(){
返回“Pojo[value=“+value+”,name=“+name+”];
}
公共双getValue(){
返回值;
}
公共无效设置值(双值){
这个值=值;
}
公共字符串getName(){
返回名称;
}
公共void集合名(字符串名){
this.name=名称;
}
/**
*@param值
*@param name
*/
公共Pojo(双值,字符串名称){
这个值=值;
this.name=名称;
}
@凌驾
公共内部比较(Pojo o){
返回((加倍)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();
}
publicstaticvoidmain(字符串[]args)引发IOException{
List pojoList=new ArrayList();
BufferedReader=newBufferedReader(newFileReader(“chat.txt”);
字符串s;
字符串[]数据;
而((s=reader.readLine())!=null){
数据=s.split(“,”);
add(新的Pojo(Double.parseDouble(数据[0]),数据[1]);
}
Collections.sort(pojoList);
FileWriter=newfilewriter(“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 {
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");
}
}
}
publicstaticvoidmain(字符串[]args)引发IOException{
ArrayList行=新的ArrayList();
ArrayList convertString=新的ArrayList();
BufferedReader reader=null;
试一试{
reader=新的BufferedReader(新的文件读取器(“C:/Temp/AvgGen.txt”);
}catch(filenotfounde异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
字符串s;
试一试{
而((s=reader.readLine())!=null){
字符串[]数据=s.split(“,”);
convertString.add;
double avg=double.parseDouble(数据[0]);
行。添加(平均值);
}
}捕获(数字格式){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
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");
}
}
}