Home > other >  Taking data from a line of another file
Taking data from a line of another file

Time:11-08

i'm creating a simple rpg game and i need to get information from one file and store it in my variables to be able to make the user save/modify items in the game easily, i can read my files but i do not know how to get the name and the numbers inside this lables:

itemName:("Steel Sword"),itemStats(2,0,0);

i need to get "Steel Sword" in a String and the numbers to the other variables...

maybe you could tell me also how to connect the name to the stats, i don't have really a good way to do it.

i tried to use indexOf to get the start and end of the string but i need to figure out the separators on the stats and maybe there's a more reliable way to do this...

CodePudding user response:

What you're looking for is to 'parse' your text file. Parsing is where you convert arbitrary data (usually human-readable text) into data your computer program can understand. Parsing custom formats (which I assume this is since I don't seem to recognise it) can be quite difficult, so you may want to consider using a more popular format such as JSON which already has plenty of libraries to parse it for you. JSON is actually pretty similar to the format you're using already, so it shouldn't be too difficult to make the switch! The data you provided could look like this in the JSON format (some minor changes can be made, for example the whitespace between values can be removed):

{"itemName": "Steel Sword", "itemStats": [2,0,0]}

CodePudding user response:

The following code makes use of an Item class so that instances of Items can be instantiated since you must have more than one Item within the file. A List Interface (List<Item>) will hold instances of Item once the file is read. Read comments in code:

The Item class:

public class Item {
    
    private String itemName;    // Item Name  
    // For lack of better member variable names since none were supplied in post.
    private int manna = 0;      // Stat 1
    private int banna = 0;      // Stat 2
    private int hanna = 0;      // Stat 3

    
    public Item() { }

    public Item(String itemName, int manna, int banna, int hanna) {
        this.itemName = itemName;
        this.manna = manna;
        this.banna = banna;
        this.hanna = hanna;
    }

    // Getters & Setters
    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }

    public int getManna() {
        return manna;
    }

    public void setManna(int manna) {
        this.manna = manna;
    }

    public int getBanna() {
        return banna;
    }

    public void setBanna(int banna) {
        this.banna = banna;
    }

    public int getHanna() {
        return hanna;
    }

    public void setHanna(int hanna) {    
        this.hanna = hanna;
    }

    @Override
    public String toString() {
        return itemName   ", "   manna   ", "   banna   ", "   hanna;
    }
}

The File Reader/Parser (getItemsFromFile()) code:

public void getItemsFromFile(String filePath) throws IOException {
    itemsList = new ArrayList<>();  // Initialize itemsList

    // Read file...
    // 'Try With Resources' used here to Auot-Close reader and free resources:
    try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();  // Remove leading/trailing whitespaces (if any);
            // Skip blank lines (if any).
            if (line.isEmpty()) {
                continue;
            }
            
            // Get Items (only) ...
            if (line.startsWith("itemName:")) {
                // Parse the Item line...
                String[] parts = line.split("itemStats");
                String name = parts[0].substring(parts[0].indexOf("(\"")   2, parts[0].indexOf("\")"));
                parts[1] = parts[1].replaceAll("[^0-9,]", "");
                String[] statValues = parts[1].split(",");
                int m = Integer.parseInt(statValues[0]);
                int b = Integer.parseInt(statValues[1]);
                int h = Integer.parseInt(statValues[2]);
                itemsList.add(new Item(name, m, b, h)); // Add Item instance to List.
            }
        }
    }
}

How you might use the above getItemsFromFile() method:

// Declare as Class member
List<Item> itemsList;  

// In some class method...
try {
    // Do as the method name states (use the proper file path):
    getItemsFromFile("GameConfig.txt");
}
catch (IOException ex) {
    /* Do what you want with the exception (if there is one).
       Whatever you do, don't leave this blank.          */
    System.err.println(ex);
}
    
//Display Items contained within the itemsList List:
for (Item items : itemsList) {
    /* Using the Item class toString() method:  */
    System.out.println(items.toString());
         
    /* Example of retrieving each object within an Item instance:
       using Item class Getter methods:                     */
    System.out.println("Item Name:  "   items.getItemName());  // String
    System.out.println("The Manna:  "   items.getManna());     // int
    System.out.println("The Banna:  "   items.getBanna());     // int
    System.out.println("The Hanna:  "   items.getHanna());     // int
    System.out.println();
}
  • Related