使用java从文本文件中读取字符串

时间:2016-03-26 13:59:57

标签: java java.util.scanner java-io

col1 col2 col3
abc 22 rome
xyz 11 spain
rome 12 uae

想要读取这个文本文件,每个列值作为单个对象来比较那些列的任意两个对象。

这是我的代码,建议一些适当的修改

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication3;

import java.util.*;
import java.io.*;

public class JavaApplication3 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException {
        try{
        Scanner s = new Scanner(new FileReader("exemple_1.txt"));

        List<String> ls1 = new ArrayList<String>(); /* to store ClosedSet values */
        List<String> ls2 = new ArrayList<String>(); /* to store Support values */ 
        List<String> ls3 = new ArrayList<String>(); /* to store ObjectList vaules */

        while(s.hasNext()){
            String[] str = s.next().split("\t");
            String s1 = str[0].trim();      /* takes ClosedSet vaues to read */
            String s2 = str[1].trim();      /* takes Support vaues to read */
            String s3= str[2].trim();       /* takes ObjectList vaues to read */

            if(!"Col1".equals(s1)){ /* skip first line */
                ls1.add(s1);
            }
            if(!"col2".equals(s2)){     /* skip first line */
                ls2.add(s2);
            }
            if(!"col3".equals(s3)){ /* skip first line */
                ls3.add(s3);
            }
        }

        System.out.println(ls2);        /* print support values */

        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } /* catch (IOException ex) {
            ex.printStackTrace();
        }   */
    }

}

1 个答案:

答案 0 :(得分:0)

如果您想逐行阅读文件,请使用s.hasNextLine()s.nextLine()。此外,equals(...)区分大小写,您已使用!"Col1".equals(s1)代替!"col1".equals(s1)