简体   繁体   English

从Java中的txt文件中以分隔线读取

[英]reading in delimited line from txt file in java

appreciate any help, I am trying to learn java and working on an exercise. 感谢您的帮助,我正在尝试学习Java并进行一项练习。 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 | MiddleName | City
Age2 | Age2 | FirstName2 | FirstName2 | MiddleName2 | MiddleName2 | City2 城市2
...... 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 年龄2
FirstName2, LastName2 FirstName2,LastName2
"Location:" City2 “位置:” 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循环的代码块-

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 | 假设文件中的所有行包含带有定界符的4个字段|

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. 您可以轻松地使用一个Person Bean来保存所有数据。

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. 如果不介意尾随空白,可以在遍历Person对象时使用增强的for循环。

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. 在您的代码中,您一次又一次地使用br.readLine(),这意味着每次都而不是只读取一个元素,而是试图读取“ new Line”,这看起来是错误的。
  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 ;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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