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

在Java中从文本文件读取数据,java,file,Java,File,我有一个包含以下内容的文本文件: 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

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

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位数。这让我陷入了困境,因为我不知道如何读取任意大小的数据。

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

<date>,<time> <integer> <double>
您可以为此使用。
它有一个构造函数,它接受
文件
,还有
next()
nextInt()
nextDouble()
方法分别读取
字符串、int、double


示例代码参考链接:

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

比如说,

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

}  

可以通过使用来完成

File File=new文件(“/yourfile.txt”);
列表行=FileUtils.readLines(文件,null);
列表项=新的ArrayList();
用于(字符串行:行){
//line==26/09/2013,16:04:40 2412-928.0
Entry=createEntry(line);//解析字符串并创建一个条目。。。
条目。添加(条目);
}
//警告,不安全也不漂亮。。。
私有静态条目createEntry(字符串行){
String[]parts=line.split(“”);
字符串[]datePart=parts[0]。拆分(“,”;
返回新条目(日期部分[0],
日期部分[1],
整数值(第[1]部分),
Double.valueOf(第[2]部分)
);
}

您目前使用的哪种方法无法实现这一点?为什么失败了?向我们展示你到目前为止所做的尝试。我建议一次只写一行,然后使用类似String#split的东西来解析这些行。从通读@SotiriosDelimanolis开始,我现在已经添加了我目前所做的内容。如何将
字符串
分配给
int
int n1=tokens[2]
?@Katona很好。我忘了分析int和double。@campari好的,我已经开始怀疑我错过了某种新的java功能
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]);  

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