我只是想做一个练习,我必须以以下格式读取名为 test.txt 的特定文件:
样本测试4
我想要做的是将文本部分存储在一个变量中,将数字存储在另一个变量中。我仍然是一个初学者,所以我必须在谷歌上进行大量搜索才能找到至少可以工作的东西,这是我到目前为止所得到的。
public static void main(String[] args) throws Exception{
try {
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
} catch(IOException e) {
System.out.println("File not found");
}
最佳答案
使用扫描仪
,这使得读取文件比 DIY 代码更容易:
try (Scanner scanner = new Scanner(new FileInputStream("test.txt"));) {
while(scanner.hasNextLine()) {
String name = scanner.next();
int number = scanner.nextInt();
scanner.nextLine(); // clears newlines from the buffer
System.out.println(str + " and " + number);
}
} catch(IOException e) {
System.out.println("File not found");
}
请注意 try-with-resources 语法的使用,该语法会在退出 try
时自动关闭扫描仪,可用是因为 Scanner
实现Closeable
。
关于Java - 从包含文本和数字的文件中读取一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43301522/