Rojin
Rojin

Reputation: 1316

How To Read A Specific Part Of A Line In A Text File In Java?

I have a text file in which I have written some information line by line like this:

name|Number|amount|PIN

How can I read back data In a way that (for example) I will be able to use just the "name" part in a method? The sample code is shown in the image below.

pic 1

pic 2

Upvotes: 0

Views: 7637

Answers (7)

binarynoise
binarynoise

Reputation: 516

in the beginning declare a List to collect the accounts:

import java.util.ArrayList;
...

public Account[] inReader() { //BTW: why do you pass an Account[] here? 
ArrayList accountList = new ArrayList();
    ...
}

replace the for(String records : dataRecords) {...} with

String name = dataRecords[0];
String cardNumber = dataRecords[1];
int pin = Integer.parseInt(dataRecords[2]); //to convert the String back to int
double balance = Double.parseDouble(dataRecords[3]);

Account account = new Account(name, cardNumber, pin, balance);
accountList.add(account);

because you already proceed record by record (while ((line = br.readLine())!=null) {...})

in the end return accountList.toArray(new Account[0]);

Upvotes: 1

Petronella
Petronella

Reputation: 2545

You can convert the file into a csv file and use a library specific for reading csv files, e.g. OpenCSV. This will give you more flexibility in handling the data in the file.

Upvotes: 0

Mark Melgo
Mark Melgo

Reputation: 1478

There are many possible ways to do it. One of them is to make an object that will hold the data. Example since you know that your data will always have name, number, amount and pin then you can make a class like this:

public class MyData {
    private String name;
    private String number;
    private double amount;
    private String pin;

    // Add getters and setters below
}

Then while reading the text file you can make a list of MyData and add each data. You can do it like this:

try {
    BufferedReader reader = new BufferedReader(new FileReader("path\file.txt"));
    String line = reader.readLine();
    ArrayList<MyData> myDataList = new ArrayList<MyData>();
    while (line != null) {
        String[] dataParts = line.split("|"); // since your delimiter is "|"
        MyData myData = new MyData();
        myData.setName(dataParts[0]);
        myData.setNumber(dataParts[1]);
        myData.setAmount(Double.parseDouble(dataParts[2]));
        myData.setPin(dataParts[3]);
        myDataList.add(myData);
        // read next line
        line = reader.readLine();
} catch (IOException e) {
    e.printStackTrace();
}

Then you can use the data like this:

myDataList.get(0).getName(); // if you want to get the name of line 1
myDataList.get(1).getPin(); // if you want to get the pin of line 2

Upvotes: 0

Marian T&#238;rlea
Marian T&#238;rlea

Reputation: 25

First, you need to read the whole content of the file or line by line. Then, for each line you need to create a function to split the line text by a configurable delimiter. This function can receive the column number and it should return the needed value. For example: extractData(line, 0) should return 'name', extractData(line, 2) should return 'amount' etc.

Also, you need some validation: what if there are only 3 columns and you expect 4? You can throw and exception or you can return null/empty.

Upvotes: 0

BeUndead
BeUndead

Reputation: 3628

As mentioned in the comment above, you can simply split the line on your delimiter, |, and go from there.

Something like:

public class Account {
    // ...
    public static Account parseLine(String line) {
        String[] split = line.split("|");
        return new Account(split[0], split[1], split[2], split[3]);
    }
}

should work fine (assuming you have a constructor which takes the four things you're putting in). If your Account class has more information than this, you can create an AccountView or similarly named class which does only contain the details you have available here. With this, just iterate line by line, parse your lines to one of these Objects, and use it's properties (including the already available getters) when calling other methods which need name, etc.

Upvotes: 0

cloying
cloying

Reputation: 365

You could read the file line-by-line and split on the delimiter '|'.

The following example assumes the filepath is in args[0] and would read then output the name component of the input:

public static void main(String[] args) {
    File file = new File(args[0]);
    BufferedReader br = new BufferedReader(new FileReader(file));

    while(String line = br.readLine()) != null) {
        String[] details = line.split("|");
        System.out.println(details[0]);
    }
}

Upvotes: 0

unit_1
unit_1

Reputation: 48

You can read the text line by line and then use the "|" delimiter to separate the columns.

try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
        stream.forEach(System.out::println);
}

Upvotes: 0

Related Questions