如何使用 Java 对文本文件中的记录进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/740936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I sort records in a text file using Java?
提问by Jessy
Some amendment of the data in txt file. I have tried the suggested code but Im not successfully write it again in the txt file with this format.I've tried the collection.sort but it write the data in long line.
对txt文件中的数据进行了一些修正。我已经尝试了建议的代码,但我没有成功地在这种格式的 txt 文件中再次写入它。我尝试了 collection.sort 但它把数据写成长行。
My txt file contain these data:
我的 txt 文件包含这些数据:
Monday
Jessica Run 20mins
Alba Walk 20mins
Amy Jogging 40mins
Bobby Run 10mins
Tuesday
Mess Run 20mins
Alba Walk 20mins
Christy Jogging 40mins
Bobby Run 10mins
How can I sort those data in ascending order and store it again in txt file after sorting?
如何按升序对这些数据进行排序并在排序后将其再次存储在 txt 文件中?
Monday
Alba Walk 20mins
Amy Jogging 40mins
Bobby Run 10mins
Jessica Run 20mins
Tuesday
Alba Walk 20mins
Bobby Run 10 mins
Christy Jogging 40mins
Mess Run 20mins
Jessica Run 20mins
回答by Aaron Maenpaa
Using sort
:
使用sort
:
aaron@ares ~$ sort data.txt
Alba Walk 20mins
Amy Jogging 40mins
Bobby Run 10mins
Jessica Run 20mins
aaron@ares ~$ sort data.txt > sorted.txt
aaron@ares ~$ cat sorted.txt
Alba Walk 20mins
Amy Jogging 40mins
Bobby Run 10mins
Jessica Run 20mins
... or using python
:
...或使用python
:
aaron@ares ~$ python -c "import sys; print ''.join(sorted(sys.stdin))" < data.txt > sorted.txt
aaron@ares ~$ cat sorted.txt
Alba Walk 20mins
Amy Jogging 40mins
Bobby Run 10mins
Jessica Run 20mins
回答by user88637
Have a class containing 3 parameters : Name , Action , and length.
有一个包含 3 个参数的类: Name 、 Action 和 length。
Open your file for reading , read word by word , for each person create a new instance of the class and fill the appropiate value then insert that instance to some collection.
打开您的文件进行阅读,逐字阅读,为每个人创建一个新的类实例并填充适当的值,然后将该实例插入到某个集合中。
Sort your collection either by writing you own sort method or (The better option) use one of the Java sorting functions.
通过编写您自己的排序方法或(更好的选择)使用其中一种 Java 排序功能对您的集合进行排序。
Open another file for writing and write your sorted collection in the same fasion.
打开另一个文件进行写入并以相同的方式写入已排序的集合。
if you can't translate the above actions into code , Buy the book "Core JAVA" and read it well Or hope someone here will be generous and give you a complete code. :)
如果你不能把上面的动作翻译成代码,买《Core JAVA》这本书好好读一读,或者希望这里有人不吝赐教,给你一个完整的代码。:)
回答by Peter Perhá?
If there isn't horrible amount of data in that file, try something like this:
如果该文件中没有可怕的数据量,请尝试以下操作:
load all of its contents into a
将其所有内容加载到一个
String s = <<file contents>>;
String[] strings = s.split(<<here comes lovely regex something like \w+\s\w+\s\w>>);
Arrays.sort(strings);
for (String str : strings) {
write str to your output file;
}
but i am much too tired to propose something more sensible....
但我太累了,无法提出更明智的建议......
回答by Peter Dolberg
Here's something I came up with:
这是我想出的东西:
import java.io.*;
import java.util.*;
public class Sort {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("fileToRead"));
Map<String, String> map=new TreeMap<String, String>();
String line="";
while((line=reader.readLine())!=null){
map.put(getField(line),line);
}
reader.close();
FileWriter writer = new FileWriter("fileToWrite");
for(String val : map.values()){
writer.write(val);
writer.write('\n');
}
writer.close();
}
private static String getField(String line) {
return line.split(" ")[0];//extract value you want to sort on
}
}
回答by llamaoo7
Here's a pretty lazy way of doing it since you are only sorting first word:
这是一种非常懒惰的方法,因为您只对第一个单词进行排序:
ArrayList<String> rows = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
String s;
while((s = reader.readLine())!=null)
rows.add(s);
Collections.sort(rows);
FileWriter writer = new FileWriter("output.txt");
for(String cur: rows)
writer.write(cur+"\n");
reader.close();
writer.close();
回答by user464703
import java.io.*;
import java.util.*;
public class Sort1 {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("fileToRead.txt"));
Map<String, String> map=new TreeMap<String, String>();
String line="";
while((line=reader.readLine())!=null){
map.put(getField(line),line);
}
reader.close();
BufferedWriter writer = new BufferedWriter(new FileWriter("fileToWrite1.txt"));
for(String val : map.values()){
writer.write(val);
writer.newLine();
}
writer.close();
}
private static String getField(String line) {
return line.split(" ")[0];//extract value you want to sort on
}
}
回答by Ibadur Rahman K
package com.myFiles;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
public class FilesReaderWriter {
public static void main(String[] args) throws IOException {
BufferedReader reader = null;
PrintWriter outputStream = null;
ArrayList<String> rows = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader("Input.txt"));
outputStream = new PrintWriter(new FileWriter("Output.txt"));
String file;
while ((file = reader .readLine()) != null) {
rows.add(file);
}
Collections.sort(rows);
String[] strArr= rows.toArray(new String[0]);
for (String cur : strArr)
outputStream.println(cur);
} finally {
if (reader != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
回答by diziaq
This solution uses Java 8 Stream API.
此解决方案使用 Java 8 Stream API。
Consider that Files.write
takes Stream<CharSequence>
as the second arg, so we need a type conversion via map(Function.identity())
.
考虑Files.write
将其Stream<CharSequence>
作为第二个参数,因此我们需要通过map(Function.identity())
.
import java.io.IOException;
import java.nio.file.*;
import java.util.function.Function;
import java.util.stream.Stream;
public class FileSortWithStreams {
public static void main(String[] args) throws IOException {
Path initialFile = Paths.get("files/initial.txt");
Path sortedFile = Paths.get("files/sorted.txt");
Stream<CharSequence> sortedLines = Files.lines(initialFile).sorted().map(Function.identity());
Files.write(sortedFile, sortedLines::iterator, StandardOpenOption.CREATE);
}
}