java - JAVA从文本文件中读取整数和坐标

标签 java

The file looks like this

我当前正在尝试的代码:

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);

}

我想读取每个数据行的数据,并能够使用它们, 例如。第一行是 10,我希望能够创建一个变量来存储它,但如果第一行是 9,我的代码将无法工作,因为我使用的是子字符串。

那么,如何读取文件,并将数据放入多个变量中? 例如我想读取第一行并将其存储在名为 room 的变量中, 读取第二行,并将其存储为firstcoordinate_x和firstcoordinate_y。

最佳答案

这是前两行的示例:

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();
    }
}

关于java - JAVA从文本文件中读取整数和坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40953278/

相关文章:

java - 如果在对话框中使用数据绑定(bind),当用户取消编辑时如何恢复数据?

java - 如何为此线程而不是系统设置 SecurityManager?

java - 使用类型参数作为方法输入

java - 引导 PropertySource 排序

java - 究竟什么是对象?这里的对象在哪里?

java - 如何在自动完成地点谷歌地图API中创建边界(仅特定地点)

Java套接字连接问题

java - Java 的编码问题

java - 为什么 Java System.in.read() 可以调用 which 不是静态方法

java - 在java中读取大txt文件时使用线程?