2021-12-11

Tech Programing

程式人小天地

Java – Reading numbers (IDs) from file in one line separated by commas

1 min read


I have two text files, items.txt and stores.txt.

items.txt is organized like this (Lines are ID, name, category)

1

The Old Man and the sea

Literature

2

Bread

Food

etc…

And stores.txt is organized in the following way (Lines are ID, name, city, Items IDs)

1

Store1

London

2,3,4,5,6

I am not sure how to read this line with items IDs in stores.txt so that they are being added into a list/set within stores.

This is what Stores look like:

public Store(String name, long id, String city, Set<Item> items) {
        super(name, id);
        this.city = city;
        this.items = items;

    }

I have created a function for items


 private static void readItemsFromFile (List <Item> items){

        try (FileReader fileReader = new FileReader(Main.ITEMS_FILE_NAME);
             BufferedReader reader = new BufferedReader(fileReader)) {

            String line;

            while ((line = reader.readLine()) != null) {
                Long id = Long.parseLong(line);
                String name = reader.readLine();
                String categoryLine=reader.readLine();

            new Item(id, name, category);

            items.add(item);

           }
        } catch (IOException e) {
            System.out.println("File " + Main.CATEGORIES_FILE_NAME + " not found.");
            logger.error(e.getMessage(), e);
        }

    }

But I am not sure how I’d solve that problem with the stores.



Source link

資料來源:Stackoverflow

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *