代码之家  ›  专栏  ›  技术社区  ›  Hristo

在使用Java读取文件时,如何从一行文本中提取名称和值?

  •  1
  • Hristo  · 技术社区  · 15 年前

    例如,如果这是文件中的一行:

    Hristo 3

    Member() 命名为Hristo,值为3。所以我想拿出一个 String 名字和名字 int 为了价值。名称和值由一些未知数量的制表符和空格分隔,我需要忽略这些制表符和空格。我能不能读一下这行,用.trim()去掉空白,最后一个字符就是值?

    为了简单起见,我没有显示类成员()。到目前为止,我的情况是:

    public static void main(String[] args) {
    
        int numMembers = 0;
        ArrayList<Member> veteranMembers = new ArrayList<Member>();
    
        File file = new File(args[0]);
        FileReader fr;
        BufferedReader br;
    
        // attempt to open and read file
        try {
            fr = new FileReader(file);
            br = new BufferedReader(fr);
    
            String line;
    
            // read file
            while ((line = br.readLine()) != null) {
    
                    // extract name and value from line
                    ... ? ...
    
                    // create member
                    // initialize name and value
                    Member member = new Member();
                    veteranMembers.add(member);
            }
            br.close();
    
        } catch (FileNotFoundException e1) {
            // Unable to find file.
            e1.printStackTrace();
        } catch (IOException e) {
            // Unable to read line.
            e.printStackTrace();
        }
    }
    

    事先谢谢你的帮助。

    4 回复  |  直到 15 年前
        1
  •  3
  •   Klark    15 年前

    你可以给它一个正则表达式作为参数 即

    line.split(" |\t");
    

    将返回单词数组(示例中为{list[0]=Hristo,list[1]=3}) 希望有帮助。

        2
  •  2
  •   Eduardo Rascon    15 年前

    split("\\s+")

        3
  •  2
  •   godheadatomic    15 年前

    更可靠的方法可能是使用正则表达式;如果收到格式错误的输入(例如,“Ted One”),parseInt()将抛出NumberFormatException。

    import java.util.regex.*;
    
    ...
    
    Pattern p = Pattern.compile("^(.*)\\s+(\\d+)$"); // Create a regex Pattern that only matches (text - white space - integer)
    Matcher m = p.matcher(line); // Create a Matcher to test the input line
    if(m.find()){
          // If there's a match, ..
        String name = m.group(1); // Set "name" to the first parenthesized group
        String value = m.group(2); // Set "value" to the second parenthesized group
    }
    else{
          // Bad Input
    }
    
        4
  •  0
  •   Teja Kantamneni    15 年前

    看起来像是家庭作业。你差一点就成功了。使用 StringTokenizer line int 使用 parseInt 转换和分配。