Reading a formatted text file in java

1.4k Views Asked by At

I mainly program in C++ and I have been working on porting my game over to Java with Android. I ran into a short problem with some of my code. My text file is in this format:

0:1 0:0 1:1 2:2 3:3   

I read it in with the fscanf function like so:

for(int Y = 0;Y < MAP_HEIGHT;Y++) {
    for(int X = 0;X < MAP_WIDTH;X++) {
        Tile tempTile;

        fscanf(FileHandle, "%d:%d ", &tempTile.TileID, &tempTile.TypeID);

        TileList.push_back(tempTile);
    }

How would I read in the formatted data shown in Java? Obviously there is no fscanf lol afaik...

2

There are 2 best solutions below

1
On

Maybe your code like this:

package test;

import java.util.Scanner;
import java.util.regex.MatchResult;

public class Test {

    public static void main(String args[]) {

        String str = "0:1 0:0 1:1 2:2 3:3";
        format(str);
    }

    public static void format(String str) {

        Scanner s = new Scanner(str);

        while (s.hasNext("(\\d):(\\d)")) {
            MatchResult mr = s.match();
            System.out.println("a=" + mr.group(1) + ";b=" + mr.group(2));
            s.next();
        }
    }
}
4
On

Use the below code to format the string in java

   import java.util.StringTokenizer;

public class Test {

    public static void main(String args[])
    {

         String str="0:1 0:0 1:1 2:2 3:3";
         format(str);
    }

    public static void format(String str) 
    {
        StringTokenizer tokens=new StringTokenizer(str, " ");  // Use Space as a Token
        while(tokens.hasMoreTokens())
        {
            String token=tokens.nextToken();
            String[] splitWithColon=token.split(":");
            System.out.println(splitWithColon[0] +" "+splitWithColon[1]);
        }

    }

}

Output of Code :

0 1
0 0
1 1
2 2
3 3