从文件中读取文本并将每行中的每个单词存储到单独的变量中 [英] reading text from file and store each word from every line into separate variables
问题描述
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和var_3变量中。
我的初始方法如下: 请给我你的建议。谢谢 I have a .txt file with the following content. 1 1111 47 2 2222 92 3 3333 81 I would like to read line-by-line and store each word into different variables.
For example : When I read first line "1 1111 47" I would like store the first word "1" into var_1, "1111" into var_2, and "47" into var_3. Then, when it goes to next line, the values should be stored into same var_1, var_2 and var_3 variables respectively. My initial approach is as follows : Kindly give me your suggestions. Thank You
这篇关于从文件中读取文本并将每行中的每个单词存储到单独的变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$ $ p $ import java.io 。*;
class ReadFromFile
{
public static void main(String [] args)throws IOException
{
int i;
FileInputStream fin;
尝试
{
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();
$ b
public static void main(String [] args)throws IOException { b $ b 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 +表示记号之间任意数量的空格
String [] tokens = line.split ( \\s +);
String var_1 = tokens [0];
String var_2 = tokens [1];
String var_3 = tokens [2];
}
}
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];
}
}