简体   繁体   中英

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.

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.

If you don't want to go the regex way, it looks like you could just get each line and split them by the numeral character. Here's an example:

public class MyTest {
    public static final void main (String[] args)
    {
        String str = "10\n" +
            "PA/1234#PV/5732#Au/9271#DT/9489#HY/7195#ZR/7413#bT/4674#LR/4992#Xk/8536#kD/9767#\n" +
            "153#25#172#95#235#159#725#629#112#559#";

        String[] arr = str.split("\n");
        ArrayList<Object[]> al = new ArrayList<>();
        String[] product = arr[1].split("#");
        String[] price = arr[2].split("#");

        for (int i = 0; i < product.length; i++)
        {
            al.add(new Object[] { product[i], Integer.parseInt(price[2]) });
        }

        System.out.println(Arrays.deepToString(al.toArray()));
    }
}

Keep in mind that I am not doing any sanity checks or exception catching/handling, which you should definitely do. This is just a quick example to get you going.

NOTE: No Validations are performed.it works only in a perfect scenario ie the if the file is in the exact same structure you mentioned

 public static void main(String[] args) { try { InputStreamReader in = new InputStreamReader(new FileInputStream("D:/productData.txt")); BufferedReader buffer = new BufferedReader(in); String readline; int line_count=0;// no of line in the file int num_of_prod = 0; float[] prod_price = null; String[] prod_code = null; while((readline=buffer.readLine())!=null){ line_count++; // read the first line from the file if(line_count==1){ // read the first line and creating the array num_of_prod = Integer.parseInt(readline); prod_code = new String[num_of_prod]; prod_price = new float[num_of_prod]; } else if(line_count==2){ prod_code = readline.split("#"); } else if(line_count == 3){ String[] string_price_arr = readline.split("#"); // converts the string array into float array for performing summation for(int i=0;i<num_of_prod;i++) prod_price[i]=Integer.parseInt(string_price_arr[i]); } } buffer.close(); System.out.println("Product code"); for(int i=0;i<num_of_prod;i++){ System.out.println(prod_code[i]); } // do the same for product price } catch (IOException e) {e.printStackTrace();} } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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