如何从文件中读取输入并逐行存储值(在Java中)?
例如,我将读取的文件是: 5,6 2,1 3,5 7,9 1,0 0,0 我首先想将整数5存储到变量“a”中,然后将整数6存储到变量“b”中,然后我想在方法中使用它们。然后我想将第二行2存储到变量“a”中,1存储到变量“b”中。所以基本上只重用两个“a”和“b”,在方法中临时使用它们,并将下一行输入存储到这些变量中,依此类推。在Java中,如何读取文件如何从文件中读取输入并逐行存储值(在Java中)?,java,file,Java,File,例如,我将读取的文件是: 5,6 2,1 3,5 7,9 1,0 0,0 我首先想将整数5存储到变量“a”中,然后将整数6存储到变量“b”中,然后我想在方法中使用它们。然后我想将第二行2存储到变量“a”中,1存储到变量“b”中。所以基本上只重用两个“a”和“b”,在方法中临时使用它们,并将下一行输入存储到这些变量中,依此类推。在Java中,如何读取文件 BufferedReader br = null; try { String sCurrentLine;
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
String [] split = sCurrentLine.split(",");
String a = split[0];
String b = split[1];
your_method(a,b);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
如果需要将值作为整数,可以使用
int aInt = Integer.parseInt(a);
int bInt = Integer.parseInt(b);
可能的重复虽然在语义上不是精确的重复,但针对该问题给出的答案也适用于此处,并且比目前提供的答案质量更好。