Search code examples
javaloopsio

Java, reading from a text file (text file has a strange format)


I know how to read data from a text file where all information is separated by lines, however this text file has a format which i am struggling to read in and loop. What i want to do is read the top line in, which is the amount of products there so i want to make an array (not ArrayList) with that many places, then read the 2nd line for a product code, then read the 3rd line for the price and repeat until all products have been added to the array.

Here is the file

productData.txt (# separates values)

10
PA/1234#PV/5732#Au/9271#DT/9489#HY/7195#ZR/7413#bT/4674#LR/4992#Xk/8536#kD/9767#
153#25#172#95#235#159#725#629#112#559#

I am struggling with this and hope that one of you can show me how it's down or point me in the right direction.


Solution

  • NOTES: I do not have the file, or a class Product with the constructor that takes in the price and the product code, but I believe that his will work.

    I had to do something similar, where I separated values in a csv file(comma separated values), so I used something similar to this.

    File productData = new File("productData.txt");
    Scanner sc = new Scanner(productData);
    Integer size = new Integer(sc.nextLine());
    Product[] products = new Product[size];
    String[] code = new String[size];
    int[] price = new int[size];
    int countLine = 0;
    
    while (sc.hasNextLine())
    {
        int count = 0;
        String line = new String(sc.nextLine());
        for (String retval: line.split("#"))
        {
            if (countLine == 0) {
                code[count] = retval;
            } else if (countLine == 1) {
                price[count] = Double.parseDouble(retval);
            }
            count++;
        }
        countLine++;
    }
    
    for (int i = 0; i < size; i++)
    {
        products[i] = new Product(code[i], price[i]);
    }
    

    What I did here was first import the file, and create a new Scanner. I made a new int called size from the integer that was in the first line. Next, I made 3 arrays. One for the final products, one for the product code, and one for the price. I also made an integer to count which line I am on. Now, I made a while loop that keeps going until there are no more lines left. I make a string called line, that is the line inside the file, and I split it up by the #. Next I made a for loop that runs through each product code/price and turns it into a string called retval(return value). Then I made an if statement where if it is on the product code line, then set each of those codes to the array, code. Otherwise, if it is on the price line, then set each of those prices to the array, price. Finally, I combine both the codes array and the prices array into the products array using the for loop.