用Java覆盖文件

时间:2014-01-29 12:59:29

标签: java text-files

try {
    BufferedReader br = new BufferedReader(new FileReader(user + ".txt"));
    String time = t.toString();

    while ((line = br.readLine()) != null) {
        String [] check = line.split(";");
        date.add(check[0]);
        timeIn.add(check[1]);
        timeOut.add(check[2]);           
    }
    br.close();

    BufferedWriter bw = new BufferedWriter(new FileWriter(user + ".txt"));

    if (timeOut.contains("not_out")){
        indx = timeOut.indexOf("not_out");
        timeOut.set(indx, time);       
    }

    for (int i = 0; i < date.size(); i++) {
        d =getDate(i);
        ti = ti(i);
        to = to(i);
        bw.write(d + ";" + ti + ";" + to);
        bw.newLine();   
    }          
    bw.close();

} catch (Exception e) {
     System.out.println("Time out error");
     e.printStackTrace();
}
return true;

文本文件的内容是:

eg. 11/22/13;8:00;8:30
    11/23/13;8:00;not_out

然后我将not_out替换为当前时间,因为我正在制作一个暂停和超时计划。 但总输出是这样的:

  11/22/13;8:00;8:30
  11/22/13;8:00;8:30
  11/23/13;8:00;8:40 

它总是复制我的第一张唱片。

1 个答案:

答案 0 :(得分:1)

这不是答案,因此被发布为“社区维基”,但您绝对需要进行一些基本的调试。你应该至少做一些事情:

try{

     BufferedReader br = new BufferedReader(new FileReader(user+".txt"));

     String time = t.toString();

     while((line=br.readLine())!=null){
         String [] check = line.split(";");
         System.out.println("check: " + java.util.Arrays.toString(check));
         date.add(check[0]);
         timeIn.add(check[1]);
         timeOut.add(check[2]);
     }
     br.close();


     BufferedWriter bw = new BufferedWriter(new FileWriter(user+".txt"));


     if(timeOut.contains("not_out")){
        indx = timeOut.indexOf("not_out");
        timeOut.set(indx, time);       
     }

     for (int i = 0 ; i <date.size();i++ ){
        d =getDate(i);
        ti= ti(i);
        to= to(i);    

        // ***** added  *****
        System.out.printf("i: %d, d: %s, ti: %s, to: %s%n", i, d, ti, to);
        bw.write(d+";"+ti+";"+to);
        bw.newLine();
     }          
     bw.close();
   } catch(Exception e){
     System.out.println("Time out error");
     e.printStackTrace();
   }
   return true;
}

您应该再向我们展示更多代码,包括ti(...)to(...)变量。

此外,你应该努力只在这里提出问题时发布格式良好的代码,使用常规的,有良好位置的缩进代码,有足够但不太多的空格(特别是没有太多的空行)。您希望我们努力使 easy 为我们提供帮助。