从文本文件中读取数据

时间:2012-12-07 09:44:18

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

我正在尝试使用文本文件作为我从用户收集的一些数据的数据库,这是我正在使用的构造函数

public DatabaseOperations(String name,double newWeight) throws FileNotFoundException, ParseException{
    f= new File (removeSpaces(name)+".txt");
    if (!f.exists()){
        System.out.println("This user dosen't exist");
        return;
    }
    try {
        out= new PrintWriter (f);
    } catch (FileNotFoundException e) {
        System.out.println("Error, You don't say");
    }
    // This section is used to initialize a new object from Customer with values in the excising file
    cust = new Customer();
    in=new Scanner(f);
    in.next();
    in.next();
    cust.setName(in.next());
    in.next();
    in.next();
    in.next();
    cust.setStartingDate(in.next());
    in.next();
    in.next();
    cust.setAge(Integer.parseInt(in.next()));
    in.next();
    in.next();
    in.next();
    cust.setStartingWeight(Double.parseDouble(in.next()));
    in.next();
    in.next();
    cust.setHeight(Double.parseDouble(in.next()));
    in.next();
    in.next();
    in.next();
    cust.setBMI(Double.parseDouble(in.next()));
    in.next();
    in.next();
    in.next();
    cust.setTargetWeight(Double.parseDouble(in.next()));
    in.next();
    in.next();
    in.next();
    cust.setTargetDate(in.next());
    //----------------------------------------------------------------
    // check this for errors !!!
    cust.setWeight(newWeight);
    out.println(form.format(cust.getCurrentDate())+"\t"+df.format(cust.getWeight())+"\t\t"+cust.getBMI()+"\t\t"+cust.percentDone()+"\t"+cust.timePassed());
    out.close();
}

这些很多in.next()用于跳过我不需要的一些数据,我正在使用的文件的结构就像那样

Name :kkkk  Started at :06/12/2012
Age :19 Starting Weight :85.0
Height :1.86        Starting BMI :24.57
Target Weight :75.5 Target Date :15/12/2012

问题是编译器抛出NoSuchElementException并指向第一个(in.next()) 另一个问题是,只要我调用此构造函数,文件就会变空!!!

2 个答案:

答案 0 :(得分:0)

String name,date,age,wight,height,....;
LineNumberReader  lnr = new LineNumberReader(new FileReader(new File("File1")));
lnr.skip(Long.MAX_VALUE);
List<String> list = new ArrayList<String>();
while(file.hasNextLine()) {
String str = file.nextLine();
String[] str1 = str.split(" ");
list.add(str1[1]);
list.add(str1[str1.length() - 1]);
}
cust.setAge(list.get(0));
.....
.....

答案 1 :(得分:0)

如果您想使用文本文件而不是数据库,我强烈建议您使用java.util.Properties类。无需使用next(),您可以使用键/值对解决此问题:http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html

Properties prop = new Properties();

try {
  prop.load(new FileInputStream(removeSpaces(name)+".txt"));
  cust.setAge(Integer.parseInt(prop.getProperty("age")));
} catch (IOException e) {
  e.printStackTrace();
}

属性text-file看起来像这样

age=19
name=kkkk
started_at=06/12/2012
starting_weight=85.0