0

i want to copy specific value from text file to Arraylist in Java Application. This is my text file( which is stored in my desktop as test.text)

String name = carrot;
double unit_price = 200;
int unit = 10;

This value i want to store in Arraylist, which is present in my main application as follow:

package com.main;
import com.collection.Ingridient;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class FileReaderApp {


    public static void main(String[] args) throws FileNotFoundException, IOException {
        Ingridient i_one = new Ingridient();
        ArrayList<Ingridient> db = new ArrayList<Ingridient>();
        FileReader fin = new FileReader("/home/yati/Desktop/test");
        Scanner src = new Scanner(fin);
// Read the ingridient from text file.
        while (src.hasNext()) {
            if (src.hasNext()) {
                i_one.setName(src.next());
                System.out.println("Name: " +src.next());
            } else
                if(src.hasNextDouble()) {
              i_one.setUnit_price(src.nextDouble());
              System.out.println("Unit Price: " +src.nextDouble());
            }
                else if (src.hasNextInt()) {
                  i_one.setUnit(src.nextInt());
                  System.out.println("Unit: " +src.nextInt());
                } else {
                    System.out.println("File format error.");
                    return;
                }
            db.add(i_one);
        }
        fin.close();

    }

}

Her, Ingridient class has following code:

package com.collection;
public class Ingridient {
    String name;
    Double unit_price;
    int unit;

    public Ingridient() {
        name = null;
        unit_price = null;
        unit = 0;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setUnit_price(Double unit_price) {
        this.unit_price = unit_price;
    }

    public void setUnit(int unit) {
        this.unit = unit;
    }    

}

My problem is that my application can store only name in Ingridient object and it cannot store any value in unit and unit_price. Obtained output is: enter image description here I know i am mistaking somewhere but i cannot solve this issue. Any Suggestion?

2
  • Is your text format fixed? None of the Strings in your text file can be parsed as a double value.
    – Aron_dc
    Oct 25, 2016 at 9:26
  • Can you tell me the right way for format the file in this context. As i was working for last night and cannot found the solution Oct 25, 2016 at 9:44

6 Answers 6

1

This should do it:

public static void main(String[] args) throws IOException {
    String content = "String name = carrot;\ndouble unit_price = 200;\nint unit = 10;";
    try (Scanner sc = new Scanner(content)) {
        sc.useDelimiter("(;*\n*.+ .+ = )|;");
        List<Incredient> incredients = new ArrayList<>();
        while (true) {
            Incrediend incredient = new Incredient();
            if (sc.hasNext()) {
                String name = sc.next();
                incredient.setName(name);
                System.out.println("Name: " + name);
            } else {
                break;
            }
            if (sc.hasNextDouble()) {
                double unitPrice = sc.nextDouble();
                incredient.setUnit_price(unitPrice);
                System.out.println("Unit Price: " + unitPrice);
            } else {
                break;
            }
            if (sc.hasNextInt()) {
                int unit = sc.nextInt();
                incredient.setUnit(unit);
                System.out.println("Unit: " + unit);
            } else {
                break;
            }
            incredients.add(incredient);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

This works because of the delimiter I've used (;*\n*.+ .+ = )|;. This pice of regex just removes all the parts of the text file that you're not interested in saving.

There are a couple of problems with your approach, for example this:

i_one.setName(src.next());
System.out.println("Name: " +src.next());

Here, you're reading 2 tokens from the scanner because there are 2 calls to next(), if you want to use the same token for multiple things you should create a new variable to store it in (ex: String name = sc.next()).

The default delimiter that the Scanner is using is a single space and because of that, in your code, hasNextDouble() and hasNextInt() will never be true, all the numbers in the text file end with ;.

I'm not sure what you're trying to do here, it is kind of unusual to parse java code from a text file. If you can change the format of the text file, you should chose one that is easier to parse (CSV for example).

2
  • It works. Thanks. Actually i try to parse content from text file and store in ArrayList. Thanks alot Oct 25, 2016 at 10:13
  • @YatishBathla I'm glad I could help.
    – Titus
    Oct 25, 2016 at 10:16
0

src.hasNext() selects every line you've got in your file, so it will never jump into one of the if/else conditions I would also recommend using json as an input format ;)

1
  • Can you provide some reference/example for this task?. Thanks Oct 25, 2016 at 9:29
0
    while (src.hasNext()) {
        if (src.hasNext()) {

it always true and another else {} sections inacessible

2
  • Can you provide the possible solution to do this task?. Thanks Oct 25, 2016 at 9:27
  • Changing the order of the if statements wont work, because the Scanner seems to split the lines at whitespace. So every number end with ";"
    – Aron_dc
    Oct 25, 2016 at 9:28
0

The structure of your text file is not very good for parsing the desired values.

If you're able to you should change it to something like

carrot,200,10

thus having all values of your desired ingredient at one line. Splitting this line at "," will give you all the values you need to instantiate your objects.

If you're not able to change the text format (because it's part of the task), you should read whole lines of the text file and interpret triples of them to get your objects. So you also can be sure that all the values you need are there.

0
0

your first if condition is wrong to get the output you need...

if (src.hasNext())

this condition will always satisfy as there will be a next object and your following else if conditions never execute. this can be seen in the output always printing the data from the sysout in the first if condition.

i have changed the code to work with startsWith method given by the string class. Hope it helps...

NOTE: before you parse it make sure you remove out those special characters if any. (Semi -colons etc.)

while (src.hasNext()) {
            String input = src.next();
            if (input.startsWith("name")) {
                i_one.setName(input);
                System.out.println("Name: " + input);
            } else if (input.startsWith("unit_price")) {
                i_one.setUnit_price(Double.parseDouble(input));
                System.out.println("Unit Price: " + input);
            } else if (input.startsWith("unit")) {
                i_one.setUnit(Integer.parseInt(input));
                System.out.println("Unit : " + input);
            } else {
                System.out.println("File format error.");
                return;
            }
            db.add(i_one);
}
2
  • The numerical values are always ending with ";" so hasNextInt or hasNextDouble would never be true.
    – Aron_dc
    Oct 25, 2016 at 9:37
  • I change the sequence but still the issue is same. It can consider everything string. Oct 25, 2016 at 9:38
0

If the structure of the text file is always the same you can use the contains method of the string class. Example:

    public class FileReaderApp {
        public static void main(String[] args) throws FileNotFoundException, IOException {
            Ingridient i_one = new Ingridient();
            ArrayList<Ingridient> db = new ArrayList<Ingridient>();

            try(BufferedReader br = new BufferedReader(new FileReader("/home/yati/Desktop/test.txt"))) {         
                String line ;
                while ((line = br.readLine())!=null) {
                    String [] splited;
                  if(line.contains("String name")){
                      splited= line.split(" ");
                      i_one.setName(splited[splited.length-1].replace(";", ""));
                      System.out.println(i_one.name);
                  }
                  else if(line.contains("double unit_price")){
                      splited= line.split(" ");
                      i_one.setUnit_price(Double.parseDouble(splited[splited.length-1].replace(";", "")));
                      System.out.println(i_one.unit_price);
                  }
                  else if(line.contains("int unit")){
                      splited= line.split(" ");
                      i_one.setUnit(Integer.parseInt(splited[splited.length-1].replace(";", "")));
                      System.out.println(i_one.unit);
                  }
                }            
            }
            db.add(i_one);
        }    
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.