从文件中读取文本并将每一行中的每个单词存储到单独的变量中 [英] Reading text from file and storing each word from every line into separate variables

查看:82
本文介绍了从文件中读取文本并将每一行中的每个单词存储到单独的变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.txt文件,其内容如下:

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.

例如:当我读第一行"1 1111 47"时,我想将第一个单词"1"存储到var_1中,将"1111"存储到var_2中,将"47"存储到var_3中.然后,当转到下一行时,这些值应分别存储到相同的var_1var_2var_3变量中.

For example: When I read the 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 the next line, the values should be stored into the same var_1, var_2 and var_3 variables respectively.

我的初始方法如下:

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];
    }
}

这篇关于从文件中读取文本并将每一行中的每个单词存储到单独的变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆