![](/img/trans.png)
[英]How to read from a file and in the file display only the lines starting with integers
[英]How to read only integers from file?
当我尝试从文本文件中读取int时,我遇到了问题。 我正在使用这种代码
import java.util.Scanner;
import java.io.*;
File fileName =new File( "D:\\input.txt");
try {
Scanner in = new Scanner(fileName);
c = in.nextInt();
n = in.nextInt();
} catch(Exception e){
System.out.println("File not Found!!!");
}
如果我的文字是这样编辑的
30
40
所以它会起作用(意思是c = 30,n = 40)。 但是如果我想编辑像这样的文本文件
c=30
n=40
我的代码不起作用。
如何更改我的代码以只读取数字并忽略“c =”和n =“或除数字之外的任何其他字符?
您需要使用Scanner.nextLine
读取行,将每行拆分为=
,然后将第二部分转换为整数。
记得在读取任何行之前进行检查 - Scanner.hasNextLine
。 因此,您需要使用while
循环来读取每一行。
一个简单的实现,您可以根据需要扩展它: -
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] tokens = line.split("=");
try {
System.out.println(Integer.parseInt(tokens[1]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
现在,如果您想稍后使用这些数字,也可以将它们添加到ArrayList<Integer>
。
按照要在输入文件中使用的格式,如果使用java.util.Properties
会更好。 您不需要关心解析。
Properties props = new Properties();
props.load(new FileInputStream(new File("D:\\input.txt")));
c = Integer.parseInt(props.getProperty("c"));
n = Integer.parseInt(props.getProperty("n"));
您可以阅读有关简单的面向行的格式的更多信息。
你可以逐行阅读( Scanner.nextLine
)并通过询问isDigit()
检查行中的每个字符
如果您的数据行始终采用相同格式x=12345
,请使用正则表达式从行中获取数值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.