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

从Java中的文本文件读取数据

  •  -1
  • Eduardo  · 技术社区  · 12 年前

    我有一个包含以下内容的文本文件:

    26/09/2013,16:04:40 2412 -928.0
    25/09/2013,14:24:30 2412 914.0
    

    上面的文件每行包含一个日期、时间、一个整数和一个双精度

    我已经创建了一个类,以便在读取数据后将其包含在内:

    public class Entry{
    
        public String date, time;
        public int integerNumber;
        public double doubleNumber;
    
        public Entry(String d, String t, int n1, double n2){
            this.date=d;
            this.time=t;
            this.integerNumber=n1;
            this.doubleNumber=n2;
        }
    }
    

    将上面的文件读取到Entry[]数组中的最佳方法是什么,其中数组中的每个元素都是来自每一行的数据?

    编辑 :我目前的尝试包括将每一行读取为字符串,并为各种数据创建子字符串,例如 String date=line.substring(0,10); 这目前很好,但当我得到整数时,它不一定是4位数。这让我陷入了困境,因为我不知道如何读取任意大小的数字。

    4 回复  |  直到 12 年前
        1
  •  3
  •   raffian Eric Reid    12 年前

    您可以使用正则表达式来读取文本文件。

    例如

    String line = "001 John Smith";  
    String regex = "(\\d)+ (\\w)+ (\\w)+";  
    Pattern pattern = Pattern.compile(regex);  
    Matcher matcher = pattern.matcher(line);  
    while(matcher.find()){  
    
        String [] group = matcher.group().split("\\s");  
        System.out.println("First Name "+group[1]);  
        System.out.println("Last Name " +group[2]);  
    
    }  
    
        2
  •  2
  •   federico-t    12 年前

    好吧,如果你能保证你正在读取的文件中的所有行都有以下格式

    <date>,<time> <integer> <double>
    

    你可以这样读

    String foo = "25/09/2013,14:24:30 2412 914.0";
    String delims = "[, ]+";
    String[] tokens = foo.split(delims);
    
    String d = tokens[0]; // d would contain the string '25/09/2013'
    String t = tokens[1]; // t would contain the string '14:24:30'
    int n1 = Integer.parseInt(tokens[2]); // n1 would contain the integer 2412
    double n2 = Double.parseDouble(tokens[3]); // n2 would contain the double 914.0
    
        3
  •  0
  •   Prabhaker A    12 年前

    您可以使用 Scanner 为此。
    它有一个构造函数 File 而且 next() , nextInt() , nextDouble() 要读取的方法 String,int,double 分别地

    对于示例代码参考链接: http://www.cs.utexas.edu/users/ndale/Scanner.html

        4
  •  0
  •   nekman    12 年前

    可以通过使用完成 Apache Commons FileUtils

    File file = new File("/yourfile.txt");
    List<String> lines = FileUtils.readLines(file, null);
    List<Entry> entries = new ArrayList<Entry>();
    for (String line : lines) {
      //line == 26/09/2013,16:04:40 2412 -928.0
      Entry entry = createEntry(line); // parse string and create a Entry...
    
      entries.add(entry);
    }
    
    // Warning, not safe and not pretty...
    private static Entry createEntry(String line) {
       String[] parts = line.split(" ");        
       String[] datePart = parts[0].split(",");
    
       return new Entry(datePart[0], 
                 datePart[1], 
                 Integer.valueOf(parts[1]),
                 Double.valueOf(parts[2])
       );
    }