Zhou
Zhou

Reputation: 11

Reading integer and coordinate from a text file in JAVA

The file looks like this

the code I am currently trying:

public static void main(String[] args) throws IOException {

    String content = new Scanner(new File("test/input_file.txt")).useDelimiter("\\z").next();
    System.out.println(content);
    String room = content.substring(0,3);
    System.out.println("room size:");
    System.out.println(room);

}

I want to read each data line of data, and be able to use them, eg. the first line is 10, I want to be able to create a variable to store it, but if the first line is 9, my code would not be working since I am using the substring.

So, How can I read the file, and put the data in multiple variables? such as I want to read the first line and store it in a variable named room, read the second line, and store it as firstcoordinate_x, and firstcoordinate_y.

Upvotes: 0

Views: 2107

Answers (1)

Eric Duminil
Eric Duminil

Reputation: 54263

Here's an example for the first two lines :

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class ParseFile
{
    public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner = new Scanner(new File("input_file.txt"));

        int roomSize = Integer.valueOf(scanner.nextLine());
        System.out.println("room size:");
        System.out.println(roomSize);

        String first_xy = scanner.nextLine();
        String[] xy = first_xy.replaceAll("\\(|\\)", "").split(",");
        int x1 = Integer.valueOf(xy[0]);
        int y1 = Integer.valueOf(xy[1]);

        System.out.println("X1:");
        System.out.println(x1);
        System.out.println("Y1:");
        System.out.println(y1);

        scanner.close();
    }
}

Upvotes: 1

Related Questions