我当前正在尝试的代码:
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/