Java 从文本文件中读取行,并通过将行中的值写入新文本文件,按平均值(平均值)对行中的值进行排序
我有一个文本文件,其中包含以下文本: Input.txt:Java 从文本文件中读取行,并通过将行中的值写入新文本文件,按平均值(平均值)对行中的值进行排序,java,arrays,sorting,text-files,java-stream,Java,Arrays,Sorting,Text Files,Java Stream,我有一个文本文件,其中包含以下文本: Input.txt: name s1 s2 s3 s4 Jack 2 4 6 5 Alex 3 5 5 5 Brian 6 6 4 5 现在布莱恩的平均得分最高:5.2;亚历克斯:4.5;杰克:4点25分。 我的任务是获得每个人的平均人数,然后按平均分数升序对他们进行排序,然后用排序后的值创建一个新的文本文件 在新文本文件中,上面的示例必须与此类似 Output.txt: name s1 s2 s3 s4 Brian 6 6 4 5 Alex 3
name s1 s2 s3 s4
Jack 2 4 6 5
Alex 3 5 5 5
Brian 6 6 4 5
现在布莱恩的平均得分最高:5.2;亚历克斯:4.5;杰克:4点25分。
我的任务是获得每个人的平均人数,然后按平均分数升序对他们进行排序,然后用排序后的值创建一个新的文本文件
在新文本文件中,上面的示例必须与此类似
Output.txt:
name s1 s2 s3 s4
Brian 6 6 4 5
Alex 3 5 5 5
Jack 2 4 6 5
到目前为止,我提出了两个解决方案,但没有一个能够完成任务
第一个是:
public class Sort {
public static void main(String[] args) throws IOException {
int sortKeyIndex = 0;
Path inputFile = Paths.get("C:\\Users\\Desktop\\sample.txt");
Path outputFile = Paths.get("C:\\Users\\Desktop\\new-sample.txt");
String separator = " ";
Stream<CharSequence> sortedLines =
Files.lines(inputFile)
.skip(1)
.map(sorting -> sorting.split(separator))
.sorted(Comparator.comparing(sorting -> sorting[sortKeyIndex]))
.map(sorting -> String.join(separator, sorting));
Files.write(outputFile, sortedLines::iterator, StandardOpenOption.CREATE);
}
}
公共类排序{
公共静态void main(字符串[]args)引发IOException{
int-sortKeyIndex=0;
Path inputFile=Path.get(“C:\\Users\\Desktop\\sample.txt”);
Path outputFile=Path.get(“C:\\Users\\Desktop\\new sample.txt”);
字符串分隔符=”;
流分类线=
Files.lines(输入文件)
.skip(1)
.map(排序->排序.split(分隔符))
.sorted(Comparator.comparing(排序->排序[sortKeyIndex]))
.map(排序->字符串.join(分隔符,排序));
write(outputFile,sortedLines::iterator,StandardOpenOption.CREATE);
}
}
第二个是:
public class SortTestSecond {
private static BufferedReader theReader;
public static void main(String[] args) throws IOException {
try {
theReader = new BufferedReader(new FileReader("C:\\Users\\Desktop\\test2.txt"));
theReader.readLine();
String currLine = null;
while((currLine = theReader.readLine()) != null) {
System.out.println(currLine);
StringTokenizer strTok = new StringTokenizer(currLine, " ");
int theCount=strTok.countTokens();
int theArray[]=new int[theCount];
int i = 0;
while(strTok.hasMoreTokens() && i != theCount) {
theArray[i]=Integer.valueOf(strTok.nextToken());
i = i + 1;
}
int theSum = 0;
for(int j =0;j < theArray.length; j++) {
theSum = theSum + theArray[j];
}
float average = (float) theSum / theArray.length;
System.out.println("Average: " + average);
}
} catch(IOException err) {
err.printStackTrace();
} finally {
theReader.close();
}
}
}
公共类排序第二{
专用静态缓冲读取器;
公共静态void main(字符串[]args)引发IOException{
试一试{
theReader=new BufferedReader(新文件阅读器(“C:\\Users\\Desktop\\test2.txt”);
reader.readLine();
字符串currLine=null;
而((currLine=theReader.readLine())!=null){
系统输出打印项次(currLine);
StringTokenizer strTok=新的StringTokenizer(currLine,“”);
int theCount=strTok.countTokens();
整数数组[]=新整数[计数];
int i=0;
while(strTok.hasMoreTokens()&&i!=计数){
数组[i]=整型.valueOf(strTok.nextToken());
i=i+1;
}
int theSum=0;
对于(int j=0;j
您必须创建一个名为Candidate的类,该类实现可比较的
class Candidate implements Comparable {
String name;
int [] values;
float average;
}
Candidate(String Name, int [] values) {
this.name = Name;
this.values = values;
this.average = getAverage();
}
public float getAverage() {
int sum = 0;
for(int c : values) {
sum += c;
}
return (float) sum/values.length;
}
@override
public int compareTo(Candidate c) {
if(c.average>this.average){
return 1;
} else {
return -1;
}
}
}
在主类中,需要为每一行创建一个对象,并使用构造函数填充
class main {
HashMap<String, Candidate> candidateList = new HashMap<String, Candidate>();
public static void main(String args[]) {
String FILENAME = "E:\\test\\filename.txt";
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
String [] currentLine = sCurrentLine.split(" ");
String name = currentLine[0];
int [] values = new int[currentLine.length-1];
for(int i=1; i<currentLine.length; i++) {
values[i-1] = Integer.valueOf(currentLine[i]);
}
Candidate c = new Candidate(name,values);
candidateList.put(name,c);// file converted to a list of candidates
}
}
}
主类{
HashMap candidateList=新建HashMap();
公共静态void main(字符串参数[]){
String FILENAME=“E:\\test\\FILENAME.txt”;
BufferedReader br=null;
FileReader fr=null;
试一试{
fr=新文件读取器(文件名);
br=新的缓冲读取器(fr);
弦电流线;
而((sCurrentLine=br.readLine())!=null){
字符串[]currentLine=sCurrentLine.split(“”);
字符串名称=当前行[0];
int[]值=新的int[currentLine.length-1];
对于(int i=1;i您可以尝试一下。首先读取文件的每一行,然后将其映射到一个Person
类。然后根据四个值的总和对每个Person
进行排序,因为它会对平均顺序进行分支。最后将排序后的对象收集为字符串
。最后是编写该String
表示排序的代码edPerson
对象到一个文件中。为此,使用Java8也是值得的
try (Stream<String> stream = Files.lines(Paths.get("C:\\data\\sample.txt"))) {
final String sortedPeople = stream.skip(1).map(l -> l.split(" "))
.map(a -> new Person(a[0], Integer.parseInt(a[1]), Integer.parseInt(a[2]), Integer.parseInt(a[3]),
Integer.parseInt(a[4])))
.sorted(Comparator.comparingInt(Person::sum).reversed()).map(Person::toString)
.collect(Collectors.joining("\n"));
System.out.println(sortedPeople);
Path path = Paths.get("C:\\data\\new-sample.txt");
byte[] strToBytes = sortedPeople.getBytes();
Files.write(path, strToBytes);
} catch (IOException e) {
e.printStackTrace();
}
public class Person {
private final String name;
private final int valOne;
private final int valTwo;
private final int valThree;
private final int valFour;
public Person(String name, int valOne, int valTwo, int valThree, int valFour) {
super();
this.name = name;
this.valOne = valOne;
this.valTwo = valTwo;
this.valThree = valThree;
this.valFour = valFour;
}
public String getName() {
return name;
}
public int getValOne() {
return valOne;
}
public int getValTwo() {
return valTwo;
}
public int getValThree() {
return valThree;
}
public int getValFour() {
return valFour;
}
public int sum() {
return this.valOne + this.valTwo + this.valThree + this.valFour;
}
@Override
public String toString() {
return name + ", " + valOne + ", " + valTwo + ", " + valThree + ", " + valFour;
}
}
您可以使用以下方法:
package com.grsdev.stackoverflow.question180629.pack01;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ScoreTransformer {
private final static String INPUT_FILE="input.txt";
private final static String OUTPUT_FILE="output.txt";
private final static String SEPARATOR=" ";
public static void main(String[] args) throws IOException, URISyntaxException {
Path inputPath=Paths.get(INPUT_FILE));
Stream<String> sorted= Files
.lines(inputPath)
.skip(1)
.map(t->PersonConvertor.parseStringToPerson(t, SEPARATOR))
.sorted((p1,p2)->(int)(p2.getAverageScore()-p1.getAverageScore()))
.map(p->PersonConvertor.convertToString(p, SEPARATOR));
Files.write(Paths.get(OUTPUT_FILE), sorted.collect(Collectors.toList()));
}
}
class PersonConvertor {
public static Person parseStringToPerson(String line,String separator) {
Person blankPerson = new Person(null, 0, 0, 0, 0);
if(line==null) return blankPerson;
String[] array = line.split(separator);
if(array.length==5) {
return new Person (array[0],Integer.parseInt(array[1]),Integer.parseInt(array[2]),Integer.parseInt(array[3]),Integer.parseInt(array[4]));
}
return blankPerson;
}
public static String convertToString(Person p,String separator) {
if(p==null)return "";
String line=p.getName()+separator+p.getScore1()+separator+p.getScore2()+ separator+p.getScore3()+separator+p.getScore4();
return line;
}
}
class Person implements Comparable<Person>{
private String name;
private int score1,score2,score3,score4;
private float averageScore;
public Person(String name, int score1, int score2, int score3, int score4) {
super();
this.name = name;
this.score1 = score1;
this.score2 = score2;
this.score3 = score3;
this.score4 = score4;
setAverageScore(((getScore1()+getScore2()+getScore3()+getScore4())/4));
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore1() {
return score1;
}
public void setScore1(int score1) {
this.score1 = score1;
}
public int getScore2() {
return score2;
}
public void setScore2(int score2) {
this.score2 = score2;
}
public int getScore3() {
return score3;
}
public void setScore3(int score3) {
this.score3 = score3;
}
public int getScore4() {
return score4;
}
public void setScore4(int score4) {
this.score4 = score4;
}
public float getAverageScore() {
return averageScore;
}
public void setAverageScore(float averageScore) {
this.averageScore = averageScore;
}
public int compareTo(Person p) {
return (int) (this.averageScore-p.getAverageScore());
}
@Override
public String toString() {
return "Person name=" + name + ", score1=" + score1 + ", score2=" + score2 + ", score3=" + score3 + ", score4="
+ score4 + ", averageScore=" + averageScore + "]";
}
}
package com.grsdev.stackoverflow.question180629.pack01;
导入java.io.IOException;
导入java.net.URISyntaxException;
导入java.nio.file.Files;
导入java.nio.file.Path;
导入java.nio.file.path;
导入java.util.stream.collector;
导入java.util.stream.stream;
公共类记分转换器{
私有最终静态字符串输入\u FILE=“INPUT.txt”;
私有最终静态字符串输出\u FILE=“OUTPUT.txt”;
私有最终静态字符串分隔符=”;
publicstaticvoidmain(字符串[]args)抛出IOException、URISyntaxException{
Path inputPath=Path.get(输入文件));
流排序=文件
.行(输入路径)
.skip(1)
.map(t->PersonConvertor.parseStringToPerson(t,分隔符))
.sorted((p1,p2)->(int)(p2.getAverageScore()-p1.getAverageScore())
.map(p->PersonConvertor.convertToString(p,分隔符));
Files.write(path.get(OUTPUT_FILE)、sorted.collect(Collectors.toList());
}
}
类个人转换器{
公共静态Person parseStringToPerson(字符串行、字符串分隔符){
Person blankPerson=新的Person(null,0,0,0,0);
if(line==null)返回blankPerson;
String[]数组=line.split(分隔符);
if(array.length==5){
返回newperson(数组[0]、Integer.parseInt(数组[1])、Integer.parseInt(数组[2])、Integer.parseInt(数组[3])、Integer.parseInt(数组[4]);
}
返回空白人;
}
公共静态字符串convertToString(Person p,字符串分隔符){
如果(p==null)返回“”;
字符串行=p.getName()+分隔符+p.getScore1()+分隔符+p.getScore2()+分隔符+p.getScore3()+分隔符+p.getScore4();
回流线;
}
}
类人实现可比性{
私有字符串名称;
个人智力1分,2分,3分,4分;
私人浮动平均分数;
公众人物(字符串名称、整数分数1、整数分数2、整数分数3、整数分数4){
超级();
this.name=名称;
这1.score1=score1;
this.score2=score2;
此点得分3=得分3;
这1.4分=4分;
setAverageScore(((getScore1()+getScore2()+getSc
package com.grsdev.stackoverflow.question180629.pack01;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ScoreTransformer {
private final static String INPUT_FILE="input.txt";
private final static String OUTPUT_FILE="output.txt";
private final static String SEPARATOR=" ";
public static void main(String[] args) throws IOException, URISyntaxException {
Path inputPath=Paths.get(INPUT_FILE));
Stream<String> sorted= Files
.lines(inputPath)
.skip(1)
.map(t->PersonConvertor.parseStringToPerson(t, SEPARATOR))
.sorted((p1,p2)->(int)(p2.getAverageScore()-p1.getAverageScore()))
.map(p->PersonConvertor.convertToString(p, SEPARATOR));
Files.write(Paths.get(OUTPUT_FILE), sorted.collect(Collectors.toList()));
}
}
class PersonConvertor {
public static Person parseStringToPerson(String line,String separator) {
Person blankPerson = new Person(null, 0, 0, 0, 0);
if(line==null) return blankPerson;
String[] array = line.split(separator);
if(array.length==5) {
return new Person (array[0],Integer.parseInt(array[1]),Integer.parseInt(array[2]),Integer.parseInt(array[3]),Integer.parseInt(array[4]));
}
return blankPerson;
}
public static String convertToString(Person p,String separator) {
if(p==null)return "";
String line=p.getName()+separator+p.getScore1()+separator+p.getScore2()+ separator+p.getScore3()+separator+p.getScore4();
return line;
}
}
class Person implements Comparable<Person>{
private String name;
private int score1,score2,score3,score4;
private float averageScore;
public Person(String name, int score1, int score2, int score3, int score4) {
super();
this.name = name;
this.score1 = score1;
this.score2 = score2;
this.score3 = score3;
this.score4 = score4;
setAverageScore(((getScore1()+getScore2()+getScore3()+getScore4())/4));
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore1() {
return score1;
}
public void setScore1(int score1) {
this.score1 = score1;
}
public int getScore2() {
return score2;
}
public void setScore2(int score2) {
this.score2 = score2;
}
public int getScore3() {
return score3;
}
public void setScore3(int score3) {
this.score3 = score3;
}
public int getScore4() {
return score4;
}
public void setScore4(int score4) {
this.score4 = score4;
}
public float getAverageScore() {
return averageScore;
}
public void setAverageScore(float averageScore) {
this.averageScore = averageScore;
}
public int compareTo(Person p) {
return (int) (this.averageScore-p.getAverageScore());
}
@Override
public String toString() {
return "Person name=" + name + ", score1=" + score1 + ", score2=" + score2 + ", score3=" + score3 + ", score4="
+ score4 + ", averageScore=" + averageScore + "]";
}
}
Path inputFile = Paths.get("C:\\Users\\Desktop\\sample.txt");
Path outputFile = inputFile.resolveSibling("new-sample.txt");
String separator = " ", newLine = System.getProperty("line.separator");
Pattern p = Pattern.compile(separator);
try(BufferedReader br = Files.newBufferedReader(inputFile);
BufferedWriter bw = Files.newBufferedWriter(outputFile, StandardOpenOption.CREATE)) {
bw.append(br.readLine()).append(newLine); // header
br.lines()
.sorted(Comparator.comparingDouble(line ->
-p.splitAsStream(line).skip(1).mapToInt(Integer::parseInt).average().orElse(-1)))
.forEachOrdered(s -> {
try { bw.append(s).append(newLine); }
catch(IOException ex) { throw new UncheckedIOException(ex); }
});
}
Path inputFile = Paths.get("C:\\Users\\Desktop\\sample.txt");
Path outputFile = inputFile.resolveSibling("new-sample.txt");
String separator = " ";
Pattern p = Pattern.compile(separator);
List<String> lines = Files.readAllLines(inputFile);
lines.subList(1, lines.size())
.sort(Comparator.comparingDouble(line ->
-p.splitAsStream(line).skip(1).mapToInt(Integer::parseInt).average().orElse(-1)));
Files.write(outputFile, lines, StandardOpenOption.CREATE);