i have a frame that contain a button and textfield.
my porpuse is read ID number frome textfield and when clicked on button, my table should display that ID with its name and mark.
my "UserSearchFile.txt" is this:
12 joe 120
14 ted 220
19 alex 560
22 julia 668
my jButton6ActionPerformed whole code is this:
int idS=Integer.parseInt(jTextField2.getText());
final Vector data = new Vector();
final Vector column = new Vector();
File f=new File("D:\\UserSearchFile.txt");
try{
FileReader fr=new FileReader(f);
BufferedReader br1=new BufferedReader(fr);
String s;
while ((s = br1.readLine()) != null) {
String[] st = s.split(" ");
String id = st[0];
String name = st[1];
String mark = st[2];
if (id.equals(String.valueOf(idS))) {
try {
String line2;
FileInputStream fis = new FileInputStream("D:\\UserSearchFile.txt");
BufferedReader br2 = new BufferedReader(new InputStreamReader(fis));
StringTokenizer st1 = new StringTokenizer(br2.readLine(), " ");
while (st1.hasMoreTokens())
column.addElement(st1.nextToken());
while ((line2 = br2.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line2, " ");
while (st2.hasMoreTokens())
data.addElement(st2.nextToken());
}
br2.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (IOException ex) {
Logger.getLogger(MainFrame1.class.getName()).log(Level.SEVERE, null, ex);
}
jTable1.setModel(new AbstractTableModel() {
public int getRowCount() {
return data.size() / getColumnCount();
}
public int getColumnCount() {
return column.size();
}
public Object getValueAt(int rowIndex, int columnIndex) {
return (String) data.elementAt((rowIndex * getColumnCount())
+ columnIndex);
}
});
jTable1.setVisible(true);
please help me and tell me how to write cleany and simple.
Start by using meaningful names for your variables and methods. jTable1, br1, br2 and jButton6ActionPerformed are not acceptable names.
Then try to split a complex method into 2 or three operations, themselves split into 2 or three operations, etc. Each operation should be a method call. For example:
private void readButtonClicked() {
String id = idTextField.getText();
Student student = findStudentWithId(id);
showStudentInGUI(student);
}
private Student findStudentWithId(String id) {
List<String> lines = readLinesInFile();
List<Student> students = transformLinesIntoStudents(lines);
Student studentWithId = findStudentWithId(students, id);
}
private Student findStudentWithId(List<Student> students, String id) {
for (Student student : students) {
if (student.getId().equals(id)) {
return student;
}
}
return null;
}
private List<Student> transformLinesIntoStudents(List<String> lines) {
List<Student> students = new ArrayList<Student>(lines.size());
for (String line : lines) {
students.add(parseStudentLine(line);
}
return students;
}
...
Related
I have included my code above. I have a buffered reader, which I am attempting to use to read textfiles.
I need Review + Restaurant otherwise I get review values printed as "null"
#Override
public Repository load(String filename) {
Repository repository = new Repository();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
//ArrayList <Review> review=new ArrayList<>();
String[] revs;
String line = br.readLine();
while(line!=null){
revs=line.split(Character.toString(DELIMITER));
int id = Integer.valueOf(revs[0]);
String name= stripQuotes(revs[1]);
String location = stripQuotes(revs[2]);
Restaurant restaurant = new Restaurant(id, name,location);
int noreview=Integer.parseInt(revs[3]);
for (int i=0; i<noreview; i++) {
line = br.readLine();
revs=line.split(Character.toString(DELIMITER));
String reviewer = stripQuotes(revs[4]);
int rating= Integer.parseInt(revs[5]);
Review review = new Review (reviewer, rating);
repository.add(restaurant);
repository.add(review);
}
}
br.close();
} catch (IOException ex) {
Logger.getLogger(DAOTextImpl.class.getName()).log(Level.SEVERE, null, ex);
}
return repository;
}
Already done this but can't make it work.
Also tried to create another while ((line = br.readLine()) != null) {}, and placed the sort before it, but it won't read this while so it wouldnt print anithing.
The file looks like this:
1-Fred-18-5-0
2-luis-12-33-0
3-Helder-23-10-0
And wanted it to print like this:
2-luis-12-33-0
3-Helder-23-10-0
1-Fred-18-5-0
public static void lerRanking() throws IOException {
File ficheiro = new File("jogadores.txt");
BufferedReader br = new BufferedReader(new FileReader(ficheiro));
List<Integer> jGanhos = new ArrayList<Integer>();
int i = 0;
String line;
String texto = "";
while ((line = br.readLine()) != null) {
String[] col = line.split("-");
int colunas = Integer.parseInt(col[3]);
jGanhos.add(colunas);
i++;
if(i>=jGanhos.size()){
Collections.sort(jGanhos);
Collections.reverse(jGanhos);
for (int j = 0; j < jGanhos.size(); j++) {
if(colunas == jGanhos.get(i)){
texto = texto + line + "\n";
}
}
}
}
PL(texto);
}
Make it step by step:
public static void lerRanking() throws IOException {
File ficheiro = new File("jodagores.txt");
// read file
BufferedReader br = new BufferedReader(new FileReader(ficheiro));
List<String> lines = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
// sort lines
lines.sort(new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// sort by 3rd column descending
return Integer.parseInt(s2.split("-")[3]) - Integer.parseInt(s1.split("-")[3]);
}
});
// concat lines
String texto = "";
for (String l : lines) {
texto += l + "\n";
}
System.out.println(texto);
// PL(texto);
}
Okay so first of all I thounk you should introduce a Java class (in my code this is ParsedObject) to manage your objects.
Second it should implement the Comparable<ParsedObject> interface, so you can easily sort it from anywhere in the code (without passing a custom comparator each time).
Here is the full code:
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
lerRanking();
}
public static void lerRanking() throws IOException {
File ficheiro = new File("jodagores.txt");
// read lines to a list
List<String> lines = readLines(ficheiro);
// parse them to a list of objects
List<ParsedObject> objects = ParsedObject.from(lines);
// sort
Collections.sort(objects);
// print the output
writeLines(objects);
}
public static List<String> readLines(File ficheiro) throws IOException {
// read file line by line
BufferedReader br = new BufferedReader(new FileReader(ficheiro));
List<String> lines = new ArrayList<>();
String line;
while((line = br.readLine()) != null) {
lines.add(line);
}
br.close(); // THIS IS IMPORTANT never forget to close a Reader :)
return lines;
}
private static void writeLines(List<ParsedObject> objects) throws IOException {
File file = new File("output.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
for(ParsedObject object : objects) {
// print the output line by line
bw.write(object.originalLine);
}
bw.flush();
bw.close(); // THIS IS IMPORTANT never forget to close a Writer :)
}
// our object that holds the information
static class ParsedObject implements Comparable<ParsedObject> {
// the original line, if needed
public String originalLine;
// the columns
public Integer firstNumber;
public String firstString;
public Integer secondNumber;
public Integer thirdNumber;
public Integer fourthNumber;
// parse line by line
public static List<ParsedObject> from(List<String> lines) {
List<ParsedObject> objects = new ArrayList<>();
for(String line : lines) {
objects.add(ParsedObject.from(line));
}
return objects;
}
// parse one line
public static ParsedObject from(String line) {
String[] splitLine = line.split("-");
ParsedObject parsedObject = new ParsedObject();
parsedObject.originalLine = line + "\n";
parsedObject.firstNumber = Integer.valueOf(splitLine[0]);
parsedObject.firstString = splitLine[1];
parsedObject.secondNumber = Integer.valueOf(splitLine[2]);
parsedObject.thirdNumber = Integer.valueOf(splitLine[3]);
parsedObject.fourthNumber = Integer.valueOf(splitLine[4]);
return parsedObject;
}
#Override
public int compareTo(ParsedObject other) {
return other.thirdNumber.compareTo(this.thirdNumber);
}
}
}
If you have any more question feel free to ask :) An here is an the example objects list after parsing and sorting.
The easiest way is to first create a class that will hold the data from your file provided your lines keep the same format
public class MyClass {
private Integer column1;
private String column2;
private Integer column3;
private Integer column4;
private Integer column5;
public MyClass(String data) {
String[] cols = data.split("-");
if (cols.length != 5) return;
column1 = Integer.parseInt(cols[0]);
column2 = cols[1];
column3 = Integer.parseInt(cols[2]);
column4 = Integer.parseInt(cols[3]);
column5 = Integer.parseInt(cols[4]);
}
public synchronized final Integer getColumn1() {
return column1;
}
public synchronized final String getColumn2() {
return column2;
}
public synchronized final Integer getColumn3() {
return column3;
}
public synchronized final Integer getColumn4() {
return column4;
}
public synchronized final Integer getColumn5() {
return column5;
}
#Override
public String toString() {
return String.format("%d-%s-%d-%d-%d", column1, column2, column3, column4, column5);
}
}
Next you can get a list of your items like this:
public static List<MyClass> getLerRanking() throws IOException {
List<MyClass> items = Files.readAllLines(Paths.get("jogadores.txt"))
.stream()
.filter(line -> !line.trim().isEmpty())
.map(data -> new MyClass(data.trim()))
.filter(data -> data.getColumn4() != null)
.sorted((o1, o2) -> o2.getColumn4().compareTo(o1.getColumn4()))
.collect(Collectors.toList());
return items;
}
This will read your whole file, filter out any blank lines, then parse the data and convert it to MyClass.
It will then make sure that column4 isn't null in the converted objects.
Finally it will reverse sort the objects based off from the value in column 4 and create a list of those items.
To print the results you can do something like this
public static void main(String[] args) {
List<MyClass> rankingList = getLerRanking();
rankingList.forEach(item -> System.out.println(item));
}
Since we overrode the toString() method, it will print it out the object as it is displayed in the file.
Hope this helps.
I am working on a java project using hibernate. I have a csv file that contains more than 200 data. I've successfully retrieved data from csv file. Now I have to insert those data to the table.
The problem is only the last row is being added to the table. Other rows are not being inserted.
The schema of the table is given below:
INSERT INTO `attendence_table`
(`serial_no` int auto-increment,
`employee_id` varchar2,
`in_time` varchar2,
`out_time` varchar2,
`attend_date` date)
The Attendence class is given below:
#Entity
#Table(name = "attendence_table")
public class Attendence {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "serial_no")
private int id;
#Column(name = "employee_id")
private String employee_id;
#Column(name = "in_time")
private String inTime;
#Column(name = "out_time")
private String outTime;
#Column(name = "attend_date")
private String date;
public String getEmployee_id() {
return employee_id;
}
public void setEmployee_id(String employee_id) {
this.employee_id = employee_id;
}
public String getInTime() {
return inTime;
}
public void setInTime(String inTime) {
this.inTime = inTime;
}
public String getOutTime() {
return outTime;
}
public void setOutTime(String outTime) {
this.outTime = outTime;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
The insert function is given below:
private static SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
public static void hibernateInsertAttendenceSession(List<Attendence> collection) {
Session session = sessionFactory.openSession();
session.beginTransaction();
for (Attendence obj : collection) {
session.save(obj);
System.out.println("Object Added");
}
session.getTransaction().commit();
session.close();
}
For your convenience, I'm also adding the glimpse of the csv file:
Test_company,TestId001,Test Name,2018/03/22,08:53:15,17:50:40
Test_company,TestId001,Test Name,2018/03/25,08:51:02,17:55:18
Test_company,TestId001,Test Name,2018/03/27,08:50:16,18:03:47
Test_company,TestId001,Test Name,2018/03/28,08:48:07,18:46:42
Test_company,TestId001,Test Name,2018/03/29,08:56:16,20:14:16
Thanks in advance for giving your valuable time to help me with this issue.
You are saving the reference of the Attendence object, while you're modifying it's content everytime.
You should probably instantiate an Attendence Object every time you attempt saving it.
for (Attendence obj : collection) {
Attendence newRef = new Attendence(obj);
session.save(newRef);
System.out.println("Object Added");
}
Sorry, My issue was in different place. Thank you all for your help. While retrieving data from csv file, there was a little error which created the issue. Thank you all for your time :)
In the readfromcsv function, previously I did the following:
public static void readFromExcel(String path) {
ArrayList<Attendence> attendences = new ArrayList<Attendence>();
String csvFile = path;
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
Attendence attendenceLine=new Attendence();
try {
br = new BufferedReader(new FileReader(csvFile));
//Attendence attendenceLine = new Attendence();
line = br.readLine();
while ((line = br.readLine()) != null) {
String[] data = line.split(cvsSplitBy);
if (data.length == 6) {
attendenceLine.setEmployee_id(data[1]);
attendenceLine.setDate(data[3]);
attendenceLine.setInTime(data[4]);
attendenceLine.setOutTime(data[5]);
}
else{
attendenceLine.setEmployee_id(data[1]);
attendenceLine.setDate(data[3]);
attendenceLine.setInTime("no punch");
attendenceLine.setOutTime("no punch");
}
attendences.add(attendenceLine);
}
for(Attendence attendence: attendences){
HibernateOperation.hibernateInsertOneAttendenceSession(attendence);
}
//HibernateOperation.hibernateInsertAttendenceSession(attendences);
} catch (FileNotFoundException ex) {
Logger.getLogger(AddToDatabaseOperation.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(AddToDatabaseOperation.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here the attendenceLine String Variable was only having the last row as a reference value. Thats why for every iteration, I need to create the object again. I did the following to solve the issue.
public static void readFromExcel(String path) {
ArrayList<Attendence> attendences = new ArrayList<Attendence>();
String csvFile = path;
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
//Attendence attendenceLine = new Attendence();
line = br.readLine();
while ((line = br.readLine()) != null) {
String[] data = line.split(cvsSplitBy);
Attendence attendenceLine=new Attendence();
if (data.length == 6) {
attendenceLine.setEmployee_id(data[1]);
attendenceLine.setDate(data[3]);
attendenceLine.setInTime(data[4]);
attendenceLine.setOutTime(data[5]);
}
else{
attendenceLine.setEmployee_id(data[1]);
attendenceLine.setDate(data[3]);
attendenceLine.setInTime("no punch");
attendenceLine.setOutTime("no punch");
}
attendences.add(attendenceLine);
}
for(Attendence attendence: attendences){
HibernateOperation.hibernateInsertOneAttendenceSession(attendence);
}
//HibernateOperation.hibernateInsertAttendenceSession(attendences);
} catch (FileNotFoundException ex) {
Logger.getLogger(AddToDatabaseOperation.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(AddToDatabaseOperation.class.getName()).log(Level.SEVERE, null, ex);
}
}
Please call new class and add all filed to this new class and save new class.
It will work.
for (Attendence obj : collection) {
Attendence newRef = new Attendence();
newRef.setSerialNo(obj.getSerialNo())
// set newRef to obj of all column......
session.save(newRef);
System.out.println("Object Added");
}
I have a code that reads an id block of three lines from a text file, I want to split those lines in Strings and an int, and pass this to a constructor from another class.
Right now, this class asks for an id number and prints everything below the # sign, down to and including the third line of each id block. I want those three lines in each id to be parsed as 'name', 'age' and 'job' to an Employee class, in order to create an object of the id, like this: Employee("Richard Smith",22,"Electric engineer"). There will always be three lines in the file for an id, so how can I "find" those lines and split them into Strings and an int?
#1000
Richard Smith
22
Electric engineer
#1001
Elliot Smith
23
Physicist
public class RdB
{
String b; //file name
RdB(String ename) {
b = ename;
}
//info about an employee
boolean showE (String id) {
int ch;
String code, info;
//open the file with the info
try (BufferedReader showERdr =
new BufferedReader (new FileReader(b)))
{
do {
//read characters until a '#' is found
ch = showERdr.read();
//check
if(ch == '#') {
code = showERdr.readLine();
if(id.compareTo(code) == 0) { //found employee
do {
info = showERdr.readLine();
if(info != null) {
System.out.println(info);
}
} while(((info != null) &&
(info.compareTo("") != 0)));
return true;
}
}
} while(ch != -1);
}
catch(IOException exc) {
System.out.println("File error!");
return false;
}
return false; //employee not found
}
//Access a registered employee
String getE() {
String id = "";
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter id number: ");
try{
id = br.readLine();
}
catch(IOException exc) {
System.out.println("Access error");
}
return id;
}
}
Edit:
Employee class
class Employee {
private String name, job;
private int age;
public Employee (String name, int age, String job) {
this.name = name;
this.age = age;
this.job = job;
}
public String getName () {
return name;
}
public int getAge () {
return age;
}
public String getJob () {
return job;
}
}
You can simply use an ArrayList to save what you read from the file and process it later. Since you are certain about the features of your saved file that it will always contain 3 lines before the line which contains ID, here is the working code I wrote to solve your problem. You can see the output wrapped between ( )
Here is the code:
import java.io.*;
import java.util.List;
import java.util.ArrayList;
public class Emp{
public static void main(String[] args) throws IOException{
List data = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("PeopleData.txt"));
String str;
while((str = reader.readLine()) != null){
// System.out.println(str);
data.add(str);
}
for(int i= 0; i< data.size(); i ++){
i++;
System.out.println("(");
System.out.println(data.get(i));
String name = (String) data.get(i);
i++;
System.out.println(data.get(i));
int age = Integer.valueOf((String) data.get(i));
i++;
System.out.println(data.get(i));
String job = (String) data.get(i);
i++;
System.out.println(")");
//new Employee(name, age, job);
}
}
}
I work at a printing company that has many programs in COBOL and I have been tasked to
convert the COBOL programs into JAVA programs. I've run into a snag in the one conversion. I need to take a file that each line is a record and on each line the data is blocked.
Example of a line is
60000003448595072410013 FFFFFFFFFFV 80 0001438001000014530020120808060134
I need to sort data by a 5 digit number at the 19-23 characters and then by the very first character on a line.
BufferedReader input;
BufferedWriter output;
String[] sort, sorted, style, accountNumber, customerNumber;
String holder;
int lineCount;
int lineCounter() {
int result = 0;
boolean eof = false;
try {
FileReader inputFile = new FileReader("C:\\Users\\cbook\\Desktop\\Chemical\\"
+ "LB26529.fil");
input = new BufferedReader(inputFile);
while (!eof) {
holder = input.readLine();
if (holder == null) {
eof = true;
} else {
result++;
}
}
} catch (IOException e) {
System.out.println("Error - " + e.toString());
}
return result;
}
chemSort(){
lineCount = this.lineCounter();
sort = new String[lineCount];
sorted = new String[lineCount];
style = new String[lineCount];
accountNumber = new String[lineCount];
customerNumber = new String[lineCount];
try {
FileReader inputFile = new FileReader("C:\\Users\\cbook\\Desktop\\Chemical\\"
+ "LB26529.fil");
input = new BufferedReader(inputFile);
for (int i = 0; i < (lineCount + 1); i++) {
holder = input.readLine();
if (holder != null) {
sort[i] = holder;
style[i] = sort[i].substring(0, 1);
customerNumber[i] = sort[i].substring(252, 257);
}
}
} catch (IOException e) {
System.out.println("Error - " + e.toString());
}
}
This what I have so far and I'm not really sure where to go from here or even if this is the correct way
to go about sorting the file. After the file is sorted it will be stored into another file and processed
again with another program for it to be ready for printing.
List<String> linesAsList = new ArrayList<String>();
String line=null;
while(null!=(line=reader.readLine())) linesAsList.add(line);
Collections.sort(linesAsList, new Comparator<String>() {
public int compare(String o1,String o2){
return (o1.substring(18,23)+o1.substring(0,1)).compareTo(o2.substring(18,23)+o2.substring(0,1));
}});
for (String line:linesAsList) System.out.println(line); // or whatever output stream you want
This phone's autocorrect is messing up my answer
Read the file into an ArrayList (instead of an array). Use the following methods:
// to declare the arraylist
ArrayList<String> lines = new ArrayList<String>();
// to add a new line to it (within your reading-lines loop)
lines.add(input.readLine());
Then, sort it using a custom Comparator:
Collections.sort(lines, new Comparator<String>() {
public int compare(String a, String b) {
String a5 = theFiveNumbersOf(a);
String b5 = theFiveNumbersOf(b);
int firstComparison = a5.compareTo(b5);
if (firstComparison != 0) { return firstComparison; }
String a1 = theDigitOf(a);
String b1 = theDigitOf(b);
return a1.compareTo(b1);
}
});
(It is unclear what 5 digits or what digit you want to compare; I've left them as functions for you to fill in).
Finally, write it to the output file:
BufferedWriter ow = new BufferedWriter(new FileOutputStream("filename.extension"));
for (String line : lines) {
ow.println(line);
}
ow.close();
(adding imports and try/catch as needed)
This code will sort a file based on mainframe sort parameters.
You pass 3 parameters to the main method of the Sort class.
The input file path.
The output file path.
The sort parameters in mainframe sort format. In your case, this string would be 19,5,CH,A,1,1,CH,A
This first class, the SortParameter class, holds instances of the sort parameters. There's one instance for every group of 4 parameters in the sort parameters string. This class is a basic getter / setter class, except for the getDifference method. The getDifference method brings some of the sort comparator code into the SortParameter class to simplify the comparator code in the Sort class.
public class SortParameter {
protected int fieldStartByte;
protected int fieldLength;
protected String fieldType;
protected String sortDirection;
public SortParameter(int fieldStartByte, int fieldLength, String fieldType,
String sortDirection) {
this.fieldStartByte = fieldStartByte;
this.fieldLength = fieldLength;
this.fieldType = fieldType;
this.sortDirection = sortDirection;
}
public int getFieldStartPosition() {
return fieldStartByte - 1;
}
public int getFieldEndPosition() {
return getFieldStartPosition() + fieldLength;
}
public String getFieldType() {
return fieldType;
}
public String getSortDirection() {
return sortDirection;
}
public int getDifference(String a, String b) {
int difference = 0;
if (getFieldType().equals("CH")) {
String as = a.substring(getFieldStartPosition(),
getFieldEndPosition());
String bs = b.substring(getFieldStartPosition(),
getFieldEndPosition());
difference = as.compareTo(bs);
if (getSortDirection().equals("D")) {
difference = -difference;
}
}
return difference;
}
}
The Sort class contains the code to read the input file, sort the input file, and write the output file. This class could probably use some more error checking.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Sort implements Runnable {
protected List<String> lines;
protected String inputFilePath;
protected String outputFilePath;
protected String sortParameters;
public Sort(String inputFilePath, String outputFilePath,
String sortParameters) {
this.inputFilePath = inputFilePath;
this.outputFilePath = outputFilePath;
this.sortParameters = sortParameters;
}
#Override
public void run() {
List<SortParameter> parameters = parseParameters(sortParameters);
lines = read(inputFilePath);
lines = sort(lines, parameters);
write(outputFilePath, lines);
}
protected List<SortParameter> parseParameters(String sortParameters) {
List<SortParameter> parameters = new ArrayList<SortParameter>();
String[] field = sortParameters.split(",");
for (int i = 0; i < field.length; i += 4) {
SortParameter parameter = new SortParameter(
Integer.parseInt(field[i]), Integer.parseInt(field[i + 1]),
field[i + 2], field[i + 3]);
parameters.add(parameter);
}
return parameters;
}
protected List<String> sort(List<String> lines,
final List<SortParameter> parameters) {
Collections.sort(lines, new Comparator<String>() {
#Override
public int compare(String a, String b) {
for (SortParameter parameter : parameters) {
int difference = parameter.getDifference(a, b);
if (difference != 0) {
return difference;
}
}
return 0;
}
});
return lines;
}
protected List<String> read(String filePath) {
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
String line;
reader = new BufferedReader(new FileReader(filePath));
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return lines;
}
protected void write(String filePath, List<String> lines) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(filePath));
for (String line : lines) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.flush();
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.err.println("The sort process requires 3 parameters.");
System.err.println(" 1. The input file path.");
System.err.println(" 2. The output file path.");
System.err.print (" 3. The sort parameters in mainframe ");
System.err.println("sort format. Example: 15,5,CH,A");
} else {
new Sort(args[0], args[1], args[2]).run();
}
}
}