java中先读取文本文档,然后对文档中的内容再对“|”后面的数字进行排序,再存入新的文本文档
展开全部
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class SortStringDemo {
public static void main(String[] args) throws IOException {
//读取文本数据
File file = new File("1.txt");
List<String> list = new ArrayList<>();
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String temp = scanner.nextLine();
if (!temp.equals("")) {
list.add(temp);
}
}
scanner.close();
// sub字符串,再使用Integer.comparTo() 如:1 2 11 这种数字大小排序
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
Integer n1 = Integer.valueOf(o1.substring(o1.indexOf("|") + 1, o1.length()));
Integer n2 = Integer.valueOf(o2.substring(o2.indexOf("|") + 1, o2.length()));
return n1.compareTo(n2);
}
});
System.out.println("按照数字大小排序:\t" + list);
// sub字符串,再使用String.comparTo() 如:1 11 2 这种按照字符串序号排序
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String string1 = o1.substring(o1.indexOf("|") + 1, o1.length());
String string2 = o2.substring(o2.indexOf("|") + 1, o2.length());
return string1.compareTo(string2);
}
});
System.out.println("按照子串排序:\t" + list);
//存储文本数据
File file2 = new File("2.txt");
PrintWriter pw = new PrintWriter(file2);
for (int i = 0; i < list.size(); i++) {
pw.println(list.get(i));
}
pw.close();
}
}
展开全部
代码如下:
import java.io.*;
import java.util.*;
public class App {
public static void main(String args[]) throws IOException {
File file = new File("data/data.txt");
List<Map.Entry<String, Integer>> list = new ArrayList<>();
// 读取
try (FileInputStream inputStream = new FileInputStream(file);
InputStreamReader streamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(streamReader)) {
String line = null;
while ((line = reader.readLine()) != null) {
String[] items = line.split("\\|");
list.add(new AbstractMap.SimpleEntry<String, Integer>(items[0], Integer.parseInt(items[1])));
}
}
// 排序
list.sort((e1, e2) -> Integer.compare(e1.getValue(), e2.getValue()));
// 保存
try (FileOutputStream outputStream = new FileOutputStream(file);
OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream);
BufferedWriter writer = new BufferedWriter(streamWriter)) {
list.forEach(entry -> {
try {
writer.write(entry.getKey() + "|" + entry.getValue() + System.lineSeparator());
} catch (IOException e) {
e.printStackTrace();
}
});
}
System.out.println("done.");
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询