简体   繁体   中英

reading in delimited line from txt file in java

appreciate any help, I am trying to learn java and working on an exercise. I am trying to read in a text file that is delimited by the pipe character, store that data either into arrays or a class in order to sort it and then finally print this sorted data back to another text file.

Example input file:
Age | FirstName | MiddleName | City
Age2 | FirstName2 | MiddleName2 | City2
...... etc

Then I want to sort this by age, oldest first. If any people in this list are the same age I want to sort them alphabetically by first name.

Finally I want to write this new sorted data to another text file such as:

Age
FirstName, LastName
"Location:" City

Age2
FirstName2, LastName2
"Location:" City2

I am kind of lost where to start with this. I started with reading in the file into an array but then wasn't sure how I would keep the data together. I guess I am looking for help on how to best go about this. Here is how I started...

import java.io.BufferedReader;
import java.io.FileReader;

public class split2 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
String line = null;

while ((line = br.readLine()) != null) {
  String[] values = line.split("\\|");
  for (String str : values) {
    System.out.println(str);
  }
}
br.close();
}}

Then I was trying to use logic like this to break it into its own data types but was having problems with it because I wasn't sure how to parse via the "|" delimiter here:

try {
        BufferedReader br = new BufferedReader(new FileReader("data.txt"));

        while (true) {
            final String line = br.readLine();
            if (line == null) break;
            age = Integer.parseInt(br.readLine());
            fname = br.readLine();
            lname = br.readLine();
            city = br.readLine();
            System.out.println(age + "\t" + fname + "\t" + lname + "\t" +     city);
        }

Any help would be much appreciated. Thank you.

You need to change your code block of while loop like below -

while (true) {
                final String line = br.readLine();
                if (line == null) break;
                String []data = line.split("\\|");
                age = Integer.parseInt(data[0]);
                fname = data[1];
                lname = data[2];
                city = data[3];
                System.out.println(age + "\t" + fname + "\t" + lname + "\t" +     city);
            }

Assuming all the lines in files containing 4 fields with delimeter |

When you need to group data in memory, a class is a great way to do that. You could easily have a Person bean to hold all your data.

class Person implements Comparable<Person> {
    private int age;
    private String firstName;
    private String lastName;
    private String city;

    public Person(int age, String firstName, String lastName, String city) {
        this.age = age;
        this.firstName = firstName;
        this.lastName = lastName;
        this.city = city;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    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 String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return age + System.lineSeparator() +
                firstName + ", " + lastName + System.lineSeparator() +
                "Location: " + city;
    }

    @Override
    public int compareTo(Person person) {
        int result = this.age - person.getAge();
        if (result == 0) {
            result = this.firstName.compareTo(person.getLastName());
        }
        return result;
    }
}

Then your reading and writing would look something like

List<Person> people = new ArrayList<>();

try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        String[] parts = line.split(" \\| ");
        people.add(new Person(Integer.parseInt(parts[0]), parts[1], parts[2], parts[3]));
    }
} catch (IOException e) {
    System.err.println("Error reading file");
}

Collections.sort(people);

try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
    for (int i = 0; i < people.size(); i++) {
        if (i > 0) {
            bw.write(System.lineSeparator());
            bw.write(System.lineSeparator());
        }
        bw.write(people.get(i).toString());
    }
} catch (IOException e) {
    System.err.println("Error writing file");
}

You could use an enhanced for loop when looping through the Person objects if you don't mind the trailing whitespace.

some changes:

import java.io.BufferedReader; 
import java.io.FileReader;

public class split2 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
String line = null;

while ((line = br.readLine()) != null) {
String[] values = line.split("\\|");

if (values.length<4) continue; // problem !!!  

String age=values[0];
String fname=values[1];
String lname=values[2];
String city=values[3];

System.out.println(age + "\t" + fname + "\t" + lname + "\t" +     city);


}
br.close();
}}

Issues with your code:-

  1. In your code you are using br.readLine() again and again, it means every time rather then read just one element, you are tring to read "new Line", that looks wrong.
  2. In your code you haven't manage any mechanism so that you can reach to exact output. Let me know if any query.

Here is your complete solution , just copy and run it on your machine,

public class PipedFile {

    public static void main(String[] args)throws Exception {
        BufferedReader br = new BufferedReader(new FileReader("C:/inputPiped.txt"));

        ArrayList<Person> list = new ArrayList<Person>();
        Person p = null;
        String readLine = br.readLine();
        while(readLine != null){
            String [] person = readLine.split("\\|");
            System.out.println(person.length);
            p = new Person();
            p.setAge(Integer.parseInt(person[0]));
            p.setFname(person[1]);
            p.setLname(person[2]);
            p.setCity(person[3]);
            list.add(p);
            readLine = br.readLine();
        }

        Collections.sort(list);

        FileOutputStream fout = new FileOutputStream("C:/ooo.txt");

        for(Person prsn : list){
            fout.write(prsn.toString().getBytes());
            fout.write('\n');
        }
        System.out.println("DONE");

    }

}

class Person implements Comparable<Person>{
    int age;
    String fname;
    String lname;
    String city;

    public int getAge() {
        return age;
    }



    public void setAge(int age) {
        this.age = age;
    }



    public String getFname() {
        return fname;
    }



    public void setFname(String fname) {
        this.fname = fname;
    }



    public String getLname() {
        return lname;
    }



    public void setLname(String lname) {
        this.lname = lname;
    }



    public String getCity() {
        return city;
    }



    public void setCity(String city) {
        this.city = city;
    }



    @Override
    public int compareTo(Person p) {

        if(this.age < p.age){
            return 1;
        }else if(this.age > p.age){
            return -1;
        }else{
            return this.fname.compareTo(p.fname);
        }

    }

    @Override
    public String toString() {
        return this.age + " | " + this.fname + " | " + this.lname + " | " + this.city ;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM