I have a problem. So I have a txt file, where is some datas. I have a class PatientView with method readInRange(PatientModel pm, Integer a, Integer b) and this class PatientModel with getter methods and one private method writeToFile() and I have a problem with this method readInRange cause I don't know how to output information between two numbers(this range must work with mediacalCard field). So what should I do to display the range using mediacalCard field? Should I make this mediacalCard an array? Please help me.
This is my code:
Class PatientView:
public void readInRange(PatientModel pm, Integer a, Integer b) {
try {
String str;
BufferedReader bufferedReader = new BufferedReader(new FileReader("test.txt"));
for (int i = a; i < b+1; i++) {
while ((str = bufferedReader.readLine()) != null) {
System.out.println(str);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Class PatientModel and his getter methods and write to file method:
public Integer getId() {
return Id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getPatronymic() {
return patronymic;
}
public String getAddress() {
return Address;
}
public Integer getNumberPhone() {
return numberPhone;
}
public Integer getMedicalCard() {
return medicalCard;
}
public String getDiagnose() {
return diagnose;
}
private void writeToFile() {
try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("test.txt", true))) {
bufferedWriter.write(String.format("%1d, %10s, %10s, %10s, %10s, %10d, %10d, %10s", Id, firstName,
lastName, patronymic, Address, numberPhone, medicalCard, diagnose));
bufferedWriter.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
Thanks everybody who tried to help me. This is how I solved this problem
My code:
public void readInRange(PatientModel pm, Integer low, Integer high) {
String[] splitdata;
String sixcol; Integer num=0;
try {
String str;
BufferedReader bufferedReader = new BufferedReader(new FileReader("test.txt"));
while ((str = bufferedReader.readLine()) != null) {
splitdata = str.split("[,\t]");
sixcol = splitdata[0];
Integer aa = num.valueOf(sixcol);
if(aa > low && aa < high) {
System.out.println(str);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Related
I have an arraylist of object type:
public static ArrayList crimes = new ArrayList();
The CityCrime.java has the following:
public class CityCrime {
//Instance variables
private String city;
private String state;
private int population;
private int murder;
private int robbery;
private int assault;
private int burglary;
private int larceny;
private int motorTheft;
public int totalCrimes;
public static void main(String[] args) {
}
public int getTotalCrimes() {
return totalCrimes;
}
public void setTotalCrimes(int murder, int robbery, int assault, int burglary, int larceny, int motorTheft) {
this.totalCrimes = murder + robbery + assault + burglary + larceny + motorTheft;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
if(state.equalsIgnoreCase("ALABAMA")) {
this.state = "AL";
}
else if(state.equalsIgnoreCase("ALASKA")) {
this.state = "AK";
}
else if(state.equalsIgnoreCase("ARIZONA")) {
this.state = "AR";
}
//etc
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public int getMurder() {
return murder;
}
public void setMurder(int murder) {
this.murder = murder;
}
public int getRobbery() {
return robbery;
}
public void setRobbery(int robbery) {
this.robbery = robbery;
}
public int getAssault() {
return assault;
}
public void setAssault(int assault) {
this.assault = assault;
}
public int getBurglary() {
return burglary;
}
public void setBurglary(int burglary) {
this.burglary = burglary;
}
public int getLarceny() {
return larceny;
}
public void setLarceny(int larceny) {
this.larceny = larceny;
}
public int getMotorTheft() {
return motorTheft;
}
public void setMotorTheft(int motorTheft) {
this.motorTheft = motorTheft;
}
public static void showAllMurderDetails() {
for (CityCrime crime : StartApp.crimes) {
System.out.println("Crime: City= " + crime.getCity() + ", Murder= " + crime.getMurder());
}
System.out.println();
}
public static int showAllViolentCrimes() {
int total = 0;
for(CityCrime crime : StartApp.crimes) {
total=total+crime.getMurder();
total=total+crime.getRobbery();
total=total+crime.getAssault();
}
System.out.println("Total of violent crimes: " + total);
return total;
}
public static int getPossessionCrimes() {
int total=0;
for (CityCrime crime : StartApp.crimes) {
total = total + crime.getBurglary();
total = total + crime.getLarceny();
total = total + crime.getMotorTheft();
}
System.out.println("Total of possession crimes: " + total);
return total;
}
}
The CityCrime ArrayList gets popular from another csv file:
public static void readCrimeData() {
File file = new File("crimeUSA.csv");
FileReader fileReader;
BufferedReader bufferedReader;
String crimeInfo;
String[] stats;
try {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
crimeInfo = bufferedReader.readLine();
crimeInfo = bufferedReader.readLine();
do {
CityCrime crime = new CityCrime(); // Default constructor
stats = crimeInfo.split(",");
{
if (stats[0] != null) {
crime.setCity(stats[0]);
}
if (stats[1] != null) {
crime.setState(stats[1]);
}
if (stats[2] != null) {
if (Integer.parseInt(stats[2]) >= 0) {
crime.setPopulation(Integer.parseInt(stats[2]));
}
}
if (stats[3] != null) {
if (Integer.parseInt(stats[3]) >= 0) {
crime.setMurder(Integer.parseInt(stats[3]));
}
}
if (stats[4] != null) {
if (Integer.parseInt(stats[4]) >= 0) {
crime.setRobbery(Integer.parseInt(stats[4]));
}
}
if (stats[5] != null) {
if (Integer.parseInt(stats[5]) >= 0) {
crime.setAssault(Integer.parseInt(stats[5]));
}
}
if (stats[6] != null) {
if (Integer.parseInt(stats[6]) >= 0) {
crime.setBurglary(Integer.parseInt(stats[6]));
}
}
if (stats[7] != null) {
if (Integer.parseInt(stats[7]) >= 0) {
crime.setLarceny(Integer.parseInt(stats[7]));
}
}
if (stats[8] != null) {
if (Integer.parseInt(stats[8]) >= 0) {
crime.setMotorTheft(Integer.parseInt(stats[8]));
}
}
crime.setTotalCrimes(Integer.parseInt(stats[3]), Integer.parseInt(stats[4]), Integer.parseInt(stats[5]), Integer.parseInt(stats[6]), Integer.parseInt(stats[7]), Integer.parseInt(stats[8]));
}
crimes.add(crime);
System.out.println(crime);
crimeInfo = bufferedReader.readLine();
} while (crimeInfo != null);
fileReader.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
I want to sort the array list and output to the csv file the list of robberies in descending order with the corresponding city. So far I have got the following, but I am stuck and not sure if going in the right direction. I'm relatively new to Java as you can probably tell so would appreciate it in as simple terms as can be:
public static void writeToFile() throws IOException {
File csvFile = new File("Robbery.csv");
FileWriter fileWriter = new FileWriter(csvFile);
ArrayList<Integer> robberyRates = new ArrayList();
for(CityCrime crime : crimes) {
robberyRates.add(crime.getRobbery());
}
Collections.sort(robberyRates);
}
The desired output will be for example:
Robbery,City
23511,New York
15863,Chicago
14353,Los Angeles
11371,Houston
10971,Philadelphia
etc…
Your help is appreciated. I have searched any page I can find on Google, but all I see from other example is writing to the csv from a set String ArrayList where they know the number of lines etc. Thankyou
You can try something like this:
public static void writeToFile() throws IOException {
File csvFile = new File("Robbery.csv");
try(FileWriter fileWriter = new FileWriter(csvFile)) { // try-with-resources to be sure that fileWriter will be closed at end
StringBuilder stringBuilder = new StringBuilder(); // Betther than String for multiple concatenation
crimes.sort(Comparator.comparingInt(CityCrime::getRobbery).reversed()); // I want to compare according to getRobbery, as Int, in reversed order
stringBuilder.append("Robbery")
.append(',')
.append("City")
.append(System.lineSeparator()); // To get new line character according to OS
for (final var crime : crimes)
stringBuilder.append(crime.getRobbery())
.append(',')
.append(crime.getCity())
.append(System.lineSeparator());
fileWriter.write(stringBuilder.toString());
}
}
If you are stuck because you can't figure out how to write a list, convert your list into a String and print the String instead.
I commented the piece of code, if you have any questions, don't hesitate.
Another solution is to use specific CSV parser library, OpenCSV for example.
It makes it easier to read and write CSV file.
Here a tutorial about OpenCSV:
https://mkyong.com/java/how-to-read-and-parse-csv-file-in-java/
I want to get user1.name variable from public static void FileRead()to private void jButton1ActionPerformed but It doesn't read user1.name. Can you explain me how can I use that variable.
public static class Users {
public String name;
public String password;
Users(String name1, String password1) {
name = name1;
password = password1;
}
}
public static void FileRead() {
try {
BufferedReader in = new BufferedReader(new FileReader("C:/Users/B_Ali/Documents/NetBeansProjects/JavaApplication20/UserNamePassword.txt"));
String[] s1 = new String[5];
String[] s2 = new String[5];
int i = 0;
while ((s1[i] = in.readLine()) != null) {
s1[i] = s2[i];
i = i + 1;
if (i == 1) {
Users user1 = new Users(s2[0], s2[1]);
}
else if (i == 3) {
Users user2 = new Users(s2[2], s2[3]);
}
else if (i == 5) {
Users user3 = new Users(s2[4], s2[5]);
}
}
in.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(LoginScreen.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(LoginScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(null, user1.name);
// TODO add your handling code here:
}
where should I declare it?
Edit: if i declare it as you said before. It becomes meaningless because i want to use user1.name which is defined in FileRead().
Declare it global.
Users user1;
public static class Users {
public String name;
public String password;
Users(String name1, String password1) {
name = name1;
password = password1;
}
public String getName()
{ return this.name;
}
public String getPassword()
{return this.password;
}
}
Users user1, user2;
public static void FileRead() {
try {
BufferedReader in = new BufferedReader(new FileReader("C:/Users/B_Ali/Documents/NetBeansProjects/JavaApplication20/UserNamePassword.txt"));
String[] s1 = new String[5];
String[] s2 = new String[5];
int i = 0;
while ((s1[i] = in.readLine()) != null) {
s1[i] = s2[i];
i = i + 1;
if (i == 1) {
Users user1 = new Users(s2[0], s2[1]);
}
else if (i == 3) {
Users user2 = new Users(s2[2], s2[3]);
}
else if (i == 5) {
Users user3 = new Users(s2[4], s2[5]);
}
}
in.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(LoginScreen.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(LoginScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(null, user1.getName());
// TODO add your handling code here:
}
You need to declare the variables you need outside of the try clause like:
String global = null;
try{
global = "abc";
throw new Exception();
}
catch(Exception e){
if (global != null){
//your code
}
}
I have a TXT file with a multiple choice question and answer(like 150 question),this is the format:
what's your name?
a. danny
b. pedro
c. jose
d. mikey
I need to seek in the file and get the questions and the answer to show them in a UI interface.
For the moment, I can read and print the file, but I don't know how to get the sentence for separate.
Any suggestion?
The code:
import java.io.*;
import java.nio.file.Path;
public class fileManager {
public FileInputStream inputStream;
public InputStreamReader reader;
public File myfile;
public String question;
public String [] answer;
public fileManager(String myfile) {
this.myfile = new File(String.valueOf(myfile));
try {
inputStream = new FileInputStream(this.myfile );
try {
reader = new InputStreamReader(inputStream , "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void printFile(){
int indexChar = 1;
char concatination = '.';
int endFile = 0;
try {
endFile = inputStream.available();
} catch (IOException e) {
e.printStackTrace();
}
do {
try {
char mychar = (char)reader.read();
if (mychar == ((char)indexChar)){
if(concatination == (char)reader.read()){
do{
System.out.print((char)reader.read());
}while ((char)reader.read() == 'א');
}
}
endFile++;
} catch (IOException e) {
e.printStackTrace();
}
}while(endFile < 1000);
}
public void closeFile(){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} //End function
public void getChar(){
}
public void getTheQuestion(){
int questionNum = 0;
int eof = 0;
int i =0;
String []file;
String question;
try {
eof = inputStream.available();
} catch (IOException e) {
e.printStackTrace();
}
for (;i == '1';){
try {
i = reader.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}//end getTheQuestion
//Getters and Setters
public FileInputStream getInputStream() {
return inputStream;
}
public void setInputStream(FileInputStream inputStream) {
this.inputStream = inputStream;
}
public File getMyfile() {
return myfile;
}
public void setMyfile(File myfile) {
this.myfile = myfile;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String[] getAnswer() {
return answer;
}
public void setAnswer(String[] answer) {
this.answer = answer;
}
}
You can accomplish it with regular expressions. Here I have written a program to help.
I have created Pattern's for questions and all four options and then fetched them.
File file = new File("myfile.txt");
Scanner sc = new Scanner(file);
Pattern questionPattern = Pattern.compile("(^(.+\\?)(?=(\\s+(a\\.\\s+.+)"
+ "\\s+b\\.\\s+.+\\s+c\\.\\s+.+\\s+d\\.\\s+.+)))", Pattern.CASE_INSENSITIVE);
Pattern optionAPattern = Pattern.compile("((?<=(.+\\?\\s))(a\\..+)(?=(\\sb\\..+$)))");
Pattern optionBPattern = Pattern.compile("((?<=(\\s))(b\\..+)(?=(\\sc\\..+$)))");
Pattern optionCPattern = Pattern.compile("((?<=(\\s))(c\\..+)(?=(\\sd\\..+$)))");
Pattern optionDPattern = Pattern.compile("((?<=(\\s))(d\\..+)(?=(\\s*$)))");
if (sc.hasNextLine()) {
String line = sc.nextLine();
Matcher question = questionPattern.matcher(line);
Matcher optionA = optionAPattern.matcher(line);
Matcher optionB = optionBPattern.matcher(line);
Matcher optionC = optionCPattern.matcher(line);
Matcher optionD = optionDPattern.matcher(line);
if(question.find()) System.out.println(question.group());
if(optionA.find()) System.out.println(optionA.group());
if(optionB.find()) System.out.println(optionB.group());
if(optionC.find()) System.out.println(optionC.group());
if(optionD.find()) System.out.println(optionD.group());
}
Output :
what's your name?
a. danny
b. pedro
c. jose
d. mikey
I think you are a beginner. Try learning regular expression to understand the code
I use the afzalex solution,
Scanner look at line, so I suppose my line start with the "index Letters"(Actually is in hebrew)so I understand its an answer, you can look at createPatterns(), and the question is not the answer so i left them, and I decide this will be in the end of the IF sentences, Where if is not empty enter to add question.
Here the code:
import com.sun.org.apache.xerces.internal.impl.xpath.regex.Match;
import java.io.*;
import java.nio.file.Path;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by aby on 11/9/14.
*/
public class fileManager {
public File myfile;
public Pattern myAnswerAlef;
public Pattern myAnswerBet;
public Pattern myAnswerGimel;
public Pattern myAnswerDalet;
public Scanner myscanner;
List<String> question = new ArrayList<String>();
List<String> answerAlef = new ArrayList<String>();
List<String> answerBet = new ArrayList<String>();
List<String> answerGimel = new ArrayList<String>();
List<String> answerDalet = new ArrayList<String>();
public fileManager(String myfile) {
this.myfile = new File(String.valueOf(myfile));
try {
myscanner = new Scanner(this.myfile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
getAnswerQuestions();
}
public void closeFile(){
myscanner.close();
} //End function
public void createPatterns(){
myAnswerAlef = Pattern.compile("[א]+[.]");
myAnswerBet = Pattern.compile("[ב]+[.]");
myAnswerGimel = Pattern.compile("[ג]+[.]");
myAnswerDalet = Pattern.compile("[ד]+[.]");
}
public void getAnswerQuestions(){
createPatterns();
do {
String line = myscanner.nextLine();
if(line.length() != 1){
Matcher MatcherAnswerAlef = myAnswerAlef.matcher(line);
Matcher MatcherAnswerBet = myAnswerBet.matcher(line);
Matcher MatcherAnswerGimel = myAnswerGimel.matcher(line);
Matcher MatcherAnswerDalet = myAnswerDalet.matcher(line);
if (MatcherAnswerAlef.find()){
answerAlef.add(line);
}
else
if (MatcherAnswerBet.find()){
answerBet.add(line);
}
else
if (MatcherAnswerGimel.find()){
answerGimel.add(line);
}
else
if (MatcherAnswerDalet.find()){
answerDalet.add(line);
}
else
if (!line.isEmpty()){
question.add(line);
}
}
else{
continue;
}
}while (myscanner.hasNext());
}
}
I have a text file, formatted as follows:
Han Solo:1000
Harry:100
Ron:10
Yoda:0
I need to make an arrayList of objects which store the player's name (Han Solo) and their score (1000) as attributes. I would like to be able to make this arrayList by reading the file line by line and splitting the string in order to get the desired attributes.
I tried using a Scanner object, but didn't get far. Any help on this would be greatly appreciated, thanks.
You can have a Player class like this:-
class Player { // Class which holds the player data
private String name;
private int score;
public Player(String name, int score) {
this.name = name;
this.score = score;
}
// Getters & Setters
// Overrride toString() - I did this. Its optional though.
}
and you can parse your file which contains the data like this:-
List<Player> players = new ArrayList<Player>();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); // I used BufferedReader instead of a Scanner
String line = null;
while ((line = br.readLine()) != null) {
String[] values = line.split(":"); // Split on ":"
players.add(new Player(values[0], Integer.parseInt(values[1]))); // Create a new Player object with the values extract and add it to the list
}
} catch (IOException ioe) {
// Exception Handling
}
System.out.println(players); // Just printing the list. toString() method of Player class is called.
You can create a Class call player. playerName and score will be the attributes.
public class Player {
private String playerName;
private String score;
// getters and setters
}
Then you can create a List
List<Player> playerList=new ArrayList<>();
Now you can try to do your task.
Additionally, you can read from file and split each line by : and put first part as playerName and second part as score.
List<Player> list=new ArrayList<>();
while (scanner.hasNextLine()){
String line=scanner.nextLine();
Player player=new Player();
player.setPlayerName(line.split(":")[0]);
player.setScore(line.split(":")[1]);
list.add(player);
}
If you have Object:
public class User
{
private String name;
private int score;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getScore()
{
return score;
}
public void setScore(int score)
{
this.score = score;
}
}
Make an Reader class that reads from the file :
public class Reader
{
public static void main(String[] args)
{
List<User> list = new ArrayList<User>();
File file = new File("test.txt");
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null)
{
String[] splitedString = line.split(":");
User user = new User();
user.setName(splitedString[0]);
user.setScore(Integer.parseInt(splitedString[1]));
list.add(user);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (reader != null)
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
for (User user : list)
{
System.out.println(user.getName()+" "+user.getScore());
}
}
}
The output will be :
Han Solo 1000
Harry 100
Ron 10
Yoda 0
Let's assume you have a class called Player that comprises two data members - name of type String and score of type int.
List<Player> players=new ArrayList<Player>();
BufferedReader br=null;
try{
br=new BufferedReader(new FileReader("filename"));
String record;
String arr[];
while((record=br.readLine())!=null){
arr=record.split(":");
//Player instantiated through two-argument constructor
players.add(new Player(arr[0], Integer.parseInt(arr[1])));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if(br!=null)
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
For small files (less than 8kb), you can use this
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class NameScoreReader {
List<Player> readFile(final String fileName) throws IOException
{
final List<Player> retval = new ArrayList<Player>();
final Path path = Paths.get(fileName);
final List<String> source = Files.readAllLines(path, StandardCharsets.UTF_8);
for (final String line : source) {
final String[] array = line.split(":");
if (array.length == 2) {
retval.add(new Player(array[0], Integer.parseInt(array[1])));
} else {
System.out.println("Invalid format: " + array);
}
}
return retval;
}
class Player {
protected Player(final String pName, final int pScore) {
super();
this.name = pName;
this.score = pScore;
}
private String name;
private int score;
public String getName()
{
return this.name;
}
public void setName(final String name)
{
this.name = name;
}
public int getScore()
{
return this.score;
}
public void setScore(final int score)
{
this.score = score;
}
}
}
Read the file and convert it to string and split function you can apply for the result.
public static String getStringFromFile(String fileName) {
BufferedReader reader;
String str = "";
try {
reader = new BufferedReader(new FileReader(fileName));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
}
str = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public static void main(String[] args) {
String stringFromText = getStringFromFile("C:/DBMT/data.txt");
//Split and other logic goes here
}
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();
}
}
}