我有一个包含以下内容的 .txt 文件:
1 1111 47
2 2222 92
3 3333 81
我想逐行读取并将每个单词存储到不同的变量中。
例如:当我读取第一行“1 1111 47”时,我想将第一个单词“1”存储到var_1
,“1111”进入var_2
,和“47”进入var_3
。然后,当它进入下一行时,这些值应该存储到相同的var_1
, var_2
and var_3
分别为变量。
我最初的做法如下:
import java.io.*;
class ReadFromFile
{
public static void main(String[] args) throws IOException
{
int i;
FileInputStream fin;
try
{
fin = new FileInputStream(args[0]);
}
catch(FileNotFoundException fex)
{
System.out.println("File not found");
return;
}
do
{
i = fin.read();
if(i != -1)
System.out.print((char) i);
} while(i != -1);
fin.close();
}
}
请给我你的建议。谢谢
public static void main(String[] args) throws IOException {
File file = new File("/path/to/InputFile");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
while( (line = br.readLine())!= null ){
// \\s+ means any number of whitespaces between tokens
String [] tokens = line.split("\\s+");
String var_1 = tokens[0];
String var_2 = tokens[1];
String var_3 = tokens[2];
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)