java - 在 Java 中覆盖文件

标签 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 

它总是复制我的第一条记录。

最佳答案

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

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(...) 变量。

此外,在此处提问时,您应该努力仅发布格式良好的代码,代码具有规则的、位置恰当的缩进,具有足够但不要太多的空格(尤其是不要太多的空行)。您希望努力让我们轻松为您提供帮助。

关于java - 在 Java 中覆盖文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21431857/

相关文章:

java - 构造函数 JsonPrimitive(Object) 不可见

c - 如何在 C 中对 .txt 文件内的数据进行排序

java - 如何使用底部导航 Activity 更改 fragment ?

java - hibernate 代理问题

java - XML 解码为 java 对象

c# - 如何使用C#读取文本文件中的日期

excel - 导入包含多行单元格的制表符分隔文本文件(到 Excel 或 Access)

java - Oracle - 如何在不格式化的情况下将 Java 项目中的时间戳插入为字符串

c# - 在 xp 上找不到文件

c - 打开和窗口