Instead of trying to assign the data to an array using separators and stuff, it is better to read all lines in a String
and then process this String
. There are plenty ways of how to read the lines of a text file into a String
. Some basic of them can be found in this question.
However, I would not split the data and "store" them into Arrays since you do not know how much your data is. Also, I would choose "a more object oriented programming way" to achieve it. I would create a class, and objects of it will represent this data. After that I'd add these objects to collection and use Java's APIs to sort it within one line.
Finally, instead of new File("C:\\Users\\bobo\\Documents\\NetBeansProjects\\" + "boombastic\\boombastic.txt");
use File
class constructor to build the path. Messing with separators is yikes...
An example would be:
public class Boombastic {
public static class Person {
private String firstName, lastName;
private int id; // ??
public Person(String firstName, String lastName, int id) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + ", id=" + id + "]";
}
}
public static void main(String[] args) throws Exception {
File desktop = new File(System.getProperty("user.home"), "Desktop");
File textFileWithData = new File(desktop, "data.txt");
List<Person> persons = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(textFileWithData))) {
String line = br.readLine();
while (line != null) {
String[] lineSplit = line.split("\\s");
Person person = new Person(lineSplit[0], lineSplit[1], Integer.parseInt(lineSplit[2]));
persons.add(person);
line = br.readLine();
}
} catch (IOException e) {
System.err.println("File cannot be read.");
e.printStackTrace();
System.exit(0);
}
// print unsorted
persons.forEach(System.out::println);
Collections.sort(persons, (p1, p2) -> p1.getId() - p2.getId()); // Sort persons by ID
System.out.println();
// print sorted
persons.forEach(System.out::println);
}
}
If you are having hard time to understand the sort part, take a look at how to use comparator in java.
My text file:
John Doe 3
Someone Else 2
Brad Pitt 5
Kevin Spacey 1
Output:
Person [firstName=John, lastName=Doe, id=3]
Person [firstName=Someone, lastName=Else, id=2]
Person [firstName=Brad, lastName=Pitt, id=5]
Person [firstName=Kevin, lastName=Spacey, id=1]
Person [firstName=Kevin, lastName=Spacey, id=1]
Person [firstName=Someone, lastName=Else, id=2]
Person [firstName=John, lastName=Doe, id=3]
Person [firstName=Brad, lastName=Pitt, id=5]