lu_lu
lu_lu

Reputation: 173

How to read a (CSV) file without separators given

I'm trying to read a text file with Java. I suppose that the reading process will be the same or at least similar to reading a CSV file. However, the data isn't separated with delimiters nor does it have a header. But I know in which position data is written (i.e. "name" can have 10 characters and is in character positions 1-10, "surname" can have 15 characters and occupies positions 11-26 and so on...)

The "name" field would be filled with 10 hyphens, if there's not data given.

How can I proceed with this type of file?

Fields: enter image description here

One line from the file that has to be read: enter image description here

First Company --------Frankfurt [email protected] 123456789 Second Company….

Upvotes: 0

Views: 883

Answers (1)

Abra
Abra

Reputation: 20914

Explanations after the code.

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

public class ParsFile {

    public static void main(String[] args) throws IOException {
        try (FileReader fr = new FileReader("input.csv");
             BufferedReader br = new BufferedReader(fr)) {
            String line = br.readLine();
            String company;
            String zip;
            String city;
            String date;
            String eMail;
            String phone;
            while (line != null) {
                company = line.substring(0, 70);
                zip = line.substring(70, 78);
                city = line.substring(78, 118);
                date = line.substring(118, 128);
                eMail = line.substring(128, 158);
                phone = line.substring(163, 203);
                line = br.readLine();
            }
        }
    }
}
  • Replace input.csv with the actual path to your file.
  • The above code simply splits each line in the file into fields according to the lengths and order of fields that you stated in your question.
  • I don't know what you want to do with the fields after you parse the line, hence I don't do anything with the variables like company and zip after assigning them a value.
  • Note that I ignored the Free field.

Upvotes: 1

Related Questions