0

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

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()) 另一个问题是,一旦我调用此构造函数,文件就会变为空!!!

4

2 回答 2

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));
.....
.....
于 2012-12-07T09:47:47.203 回答
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();
}

属性文本文件看起来像这样

age=19
name=kkkk
started_at=06/12/2012
starting_weight=85.0
于 2012-12-07T09:47:58.787 回答