Java-文本到数组到文本
我正在寻找从一个小文本文件中读取整数+字符串的最佳方法,将它们保存在数组中,添加一些新的整数+字符串,按整数排序,然后在同一文件中写入最高数。(像高分一样) 例子: sth.txt: 进入 添加一些新字符串Java-文本到数组到文本,java,string,sorting,io,integer,Java,String,Sorting,Io,Integer,我正在寻找从一个小文本文件中读取整数+字符串的最佳方法,将它们保存在数组中,添加一些新的整数+字符串,按整数排序,然后在同一文件中写入最高数。(像高分一样) 例子: sth.txt: 进入 添加一些新字符串 a["5 aa","4 bb","3 cc","3 dd","1 aa","7 bb"] 整理并写回某物 如何在Java中实现这一点?您可以按照以下操作,代码中包含注释,
a["5 aa","4 bb","3 cc","3 dd","1 aa","7 bb"]
整理并写回某物
如何在Java中实现这一点?您可以按照以下操作,代码中包含注释,以便更好地理解。
public static void main(String[] args) throws IOException {
Data[] map = new Data[6];
//Then read the data from your file , in my case
//i will make a dummy data.
map[0] = new Data(5, "aa");
map[1] = new Data(4, "bb");
map[2] = new Data(3, "cc");
map[3] = new Data(3, "dd");
map[4] = new Data(1, "aa");
map[5] = new Data(7, "bb");
//Then sorting this array
java.util.Arrays.sort(map);
//Then print the highet 4 records
for (int i = 0; i < 4; i++) {
System.out.println(map[i].FirstPart + " " + map[i].SecondPart);
}
}
输出:
7 bb
5 aa
4 bb
3 dd
以下是示例解决方案,包括读取和写入文件:
public class Main {
static class Entry<T, U> {
public T value1;
public U value2;
public Entry(T value1, U value2) {
this.value1 = value1;
this.value2 = value2;
}
}
static Entry<Integer, String> parseLine(String line) {
String[] intAndString = line.split(" ");
Integer i = Integer.parseInt(intAndString[0]);
String s = intAndString[1];
return new Entry<>(i, s);
}
public static void main(String[] args) throws IOException {
Path path = Paths.get("spl.txt");
List<Entry<Integer, String>> resultList = new LinkedList<>();
try (BufferedReader reader = Files.newBufferedReader(path)) {
String nextLine;
while ((nextLine = reader.readLine()) != null) {
if (nextLine.equals("\n") || nextLine.isEmpty()) continue;
resultList.add(parseLine(nextLine));
}
}
Collections.sort(resultList, (e1, e2) -> e1.value1 - e2.value1 != 0 ? e1.value1 - e2.value1 : e1.value2.compareTo(e2.value2));
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
resultList.forEach((e) -> {
try {
writer.write(e.value1 + " " + e.value2 + "\n");
} catch (IOException e1) {
e1.printStackTrace();
}
});
}
}
}
公共类主{
静态类条目{
公共价值1;
公共价值2;
公众进入(T值1,U值2){
此值为1.value1=value1;
此参数为0.value2=value2;
}
}
静态条目解析行(字符串行){
String[]intAndString=line.split(“”);
整数i=Integer.parseInt(intAndString[0]);
字符串s=intAndString[1];
返回新条目;
}
公共静态void main(字符串[]args)引发IOException{
Path Path=Path.get(“spl.txt”);
List resultList=新建LinkedList();
try(BufferedReader=Files.newBufferedReader(路径)){
字符串下一行;
而((nextLine=reader.readLine())!=null){
如果(nextLine.equals(“\n”)| | nextLine.isEmpty())继续;
add(parseLine(nextLine));
}
}
Collections.sort(resultList,(e1,e2)->e1.value1-e2.value1!=0?e1.value1-e2.value1:e1.value2.compareTo(e2.value2));
try(BufferedWriter=Files.newBufferedWriter(路径)){
结果列表forEach((e)->{
试一试{
writer.write(e.value1+“”+e.value2+“\n”);
}捕获(IOE1异常){
e1.printStackTrace();
}
});
}
}
}
由于可读性,省略了类条目的封装。按升序排序。
希望能有所帮助。检查下面的解决方案--
试试Java映射,它将允许您将字符串与分数关联。关于如何用Java读取文本文件、如何在数组(或列表)中存储数据、如何对数组/列表排序以及如何将文本写入文件,有很多问题。您对哪一步有问题?向我们展示您的代码并描述您面临的具体问题。使用类解析测试文件并使用该类的列表,然后使用Collections.sort和自定义比较器!你能做到吗?@RAZ_Muh_Taz对不起,我应该从这个开始。我试着先读/写不同的文件,然后找到了10种不同的方法,然后在某个地方迷路了。我的最新尝试,也是我认为最成功的尝试:如果两个对象具有相等的
第一部分怎么办?我们应该交换这些元素吗?无论如何,您不需要手动编写条件。让Integer。比较为您执行此操作,并简单地返回其结果。如果两个对象的第一部分相等,则他可以执行第一次出现>>第一次显示
,反之亦然。甚至他也可以根据第二部分进行排序。这都是关于@PshemoYeah所需的OP,看起来也不错,我会尝试修复错误并回答@Pshemo我不太精确,但这没关系。我担心的是,显示的比较不尊重排序规则。通常如果A>B
这意味着BYeah,那几乎就是我想要的。问题是,它们写在一行中,没有可见的分隔符(如“\n”不起作用),所以我用[enter]将它们分隔,然后保存并重新运行应用程序,结果出现了一个严重的异常:。我不明白为什么,因为它们最初是用[enter]分隔的。问题在于文件末尾的新行符号,请检查我的新解决方案。不知何故,它对我仍然有效-返回一行中的字符串并以新行结尾,就像“\n”只在结尾起作用,而且似乎在某处添加了空字符,因为每当我在它们之间插入回车符并在末尾删除新行符号时(选中-我是否删除它并不重要),我就会得到上面提到的异常。好的,我更改了它。但请记住,它适用于您给出的格式:数字字符串和后面的新行,例如:“5 aa”是的,文件的可读性总是很好,但结果总是像C的所有行的strcpy,像“1 aa2 aa3 aa”+结尾的新行。在我用[enter]分隔行、删除末尾的新行、保存文件、关闭文件并重新运行后,它总是抛出该异常。在我从文本文件中删除整个文本并手动重新键入后,它不会引发异常,但结果是相同的。也检查了那个,还是一样。不过,我不知道为什么,就我对Java的理解而言,您的代码对我来说似乎是合法的。这一个对我来说很有用。我将尝试在读和写之间添加一些新字符串,然后将“newabc.txt”复制到“abc.txt”中,并告诉它是如何工作的。当然,也可以发布您的结果。
public static void main(String[] args) throws IOException {
Data[] map = new Data[6];
//Then read the data from your file , in my case
//i will make a dummy data.
map[0] = new Data(5, "aa");
map[1] = new Data(4, "bb");
map[2] = new Data(3, "cc");
map[3] = new Data(3, "dd");
map[4] = new Data(1, "aa");
map[5] = new Data(7, "bb");
//Then sorting this array
java.util.Arrays.sort(map);
//Then print the highet 4 records
for (int i = 0; i < 4; i++) {
System.out.println(map[i].FirstPart + " " + map[i].SecondPart);
}
}
class Data implements Comparable<Data> {
int FirstPart;
String SecondPart;
public Data(int FirstPart, String SecondPart) {
this.FirstPart = FirstPart;
this.SecondPart = SecondPart;
}
//compareTo method will be called whenever you call a sort method like
// "java.util.Arrays.sort(map);" in the main method
@Override
public int compareTo(Data o) {
if (this.FirstPart < o.FirstPart) {
return 1;
} else {
return -1;
}
}
}
7 bb
5 aa
4 bb
3 dd
public class Main {
static class Entry<T, U> {
public T value1;
public U value2;
public Entry(T value1, U value2) {
this.value1 = value1;
this.value2 = value2;
}
}
static Entry<Integer, String> parseLine(String line) {
String[] intAndString = line.split(" ");
Integer i = Integer.parseInt(intAndString[0]);
String s = intAndString[1];
return new Entry<>(i, s);
}
public static void main(String[] args) throws IOException {
Path path = Paths.get("spl.txt");
List<Entry<Integer, String>> resultList = new LinkedList<>();
try (BufferedReader reader = Files.newBufferedReader(path)) {
String nextLine;
while ((nextLine = reader.readLine()) != null) {
if (nextLine.equals("\n") || nextLine.isEmpty()) continue;
resultList.add(parseLine(nextLine));
}
}
Collections.sort(resultList, (e1, e2) -> e1.value1 - e2.value1 != 0 ? e1.value1 - e2.value1 : e1.value2.compareTo(e2.value2));
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
resultList.forEach((e) -> {
try {
writer.write(e.value1 + " " + e.value2 + "\n");
} catch (IOException e1) {
e1.printStackTrace();
}
});
}
}
}
abc.txt
4 test1
6 test2
0 test3
12 test4
5 test5
9 test6
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
public class ReadWriteDataInFile {
public static void main(String[] args) throws IOException {
String path="C:\\test\\";
String fileName=path+"abc.txt";
String newFileName=path+"abcNew.txt";
System.out.println("Reading Data from File "+fileName + " started...");
Map<Integer, String> readDataFromTextFile = readDataFromTextFile(fileName);
System.out.println("Writing Sorted Data to File "+newFileName + " started...");
writeDataInNewFile(readDataFromTextFile,newFileName);
System.out.println("Writing Data to File Completed...");
}
private static void writeDataInNewFile(Map<Integer, String> readDataFromTextFile, String newFileName) throws IOException {
PrintWriter writer = new PrintWriter(newFileName, "UTF-8");
Iterator it = readDataFromTextFile.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
String data1=pair.getKey() + " " + pair.getValue();
writer.println(data1);
}
writer.close();
}
private static Map<Integer, String> readDataFromTextFile(String fileName) throws IOException {
FileInputStream fis = new FileInputStream(fileName);
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result[] ;
Map<Integer,String> dataMap= new TreeMap<Integer,String> ();
while ((data = br.readLine()) != null) {
result = data.split(" ");
dataMap.put(Integer.parseInt(result[0]), result[1]);
}
return dataMap;
}
}
newabc.txt
0 test3
4 test1
5 test5
6 test2
9 test6
12 test4