How to correctly split new line in text file (Java)?

56 views Asked by At

I need a quick help with my code. I think it all works fine, but I have just one problem. I need to split every line of text file and add each of them to array. This assignment is about using RandomAccessFile class. And problem is - I can't split these lines from text file. It only says that each array is null.

I was typing any regex that I found online into String.split. Nothing works. I was also trying to use Scanner, but it went much worse.

try(RandomAccessFile raf = new RandomAccessFile("domy.txt", "rw")){
        while((str = raf.readLine()) != null){
            String[] data = new String[100];
            data = str.split("\n");
            String name = data[0];
            String floors = data[1];
            String price = data[2];
            String location = data[3];
            System.out.println(data[0] + " " + data[1] + " " + data[2] + " " + data[3]);

            if(floors.equals("1") && location.equals("Wies")){
                var floorsInt = Integer.parseInt(floors);
                var priceDouble = Double.parseDouble(price);
                raf.seek(raf.getFilePointer() - str.length());
                raf.writeBytes(name + "\n" + floorsInt + "\n" + df.format(priceDouble * 0.9) + "\n" + location);
            }
        }
    }
    catch(FileNotFoundException e){
        e.printStackTrace();

The most common errors are "Index 1 out of bounds for length 1" and "floors is empty"

Willa
3
1000000.00
Miasto
Chata
1
99999.99
Wies

Here is what I have in a text file

0

There are 0 answers