Reputation: 1
I have a text file like down below:
jack; 488;22;98
kylie; 541;72;81
jenna; 995;66;17 .
.
The list is formatted as follows:
On every line, the first number after the name is the student's code and the numbers following it are scores.
I want to pass the student's code (as a String
) as the input to the program and it should return the student's second score to me.
I have tried bufferedreader
,but I can just write all text files as output, but I can't search for the code and the other things.
Thanks
Upvotes: 0
Views: 69
Reputation: 1083
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class FilterCsv {
private class Student {
private String name;
private String code;
private String score;
private String score2;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
public String getScore2() {
return score2;
}
public void setScore2(String score2) {
this.score2 = score2;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", code='" + code + '\'' +
", score='" + score + '\'' +
", score2='" + score2 + '\'' +
'}';
}
}
private Function<String, Student> mapToItem = (line) -> {
System.out.println(line);
String[] p = line.split(";");
Student student = new Student();
student.setName(p[0]);
if (p[1] != null && p[1].trim().length() > 0) {
student.setCode(p[1]);
}
if (p[2] != null && p[2].trim().length() > 0) {
student.setScore(p[2]);
}
if (p[3] != null && p[3].trim().length() > 0) {
student.setScore2(p[3]);
}
return student;
};
private List<Student> processInputFile(String inputFilePath, String name) {
List<Student> inputList = new ArrayList<>();
try {
File inputF = new File(inputFilePath);
InputStream inputFS = new FileInputStream(inputF);
BufferedReader br = new BufferedReader(new InputStreamReader(inputFS));
// skip the header of the csv
inputList = br.lines().map(mapToItem).collect(Collectors.toList());
br.close();
String secondScore = inputList
.stream()
.peek(System.out::println)
.filter((s -> s.getName().equals(name)))
.findFirst()
.get().getScore2();
System.out.println("Score 2 for " + name + " is: " + secondScore);
} catch (IOException e) {
System.out.println(e);
}
return inputList;
}
public static void main(String[] args) {
new FilterCsv().processInputFile("your filepath, "studentsName");
}
}
add some error checking and stuff... Cheers
Upvotes: 0
Reputation: 589
BufferedReader br = new BufferedReader(new FileReader("filePath"));
String contentLine = br.readLine();
while (contentLine != null) {
String[] result=contentLine.split(";");
String studentCode =result[1].trim();
// apply your logic for studentCode here
contentLine = br.readLine();
}
Upvotes: 2