Java读/写,重命名文件有问题

时间:2015-04-11 03:16:51

标签: java

我正在使用我的代码来执行替换线功能。它最初工作,但突然我的新文件变成空白,代码没有让我回到AdminMenu(),以及没有重命名的文件。还有另一个问题,如果我使用"\r\n",我的文件顶部会有一个空白行,我试图删除。我在\n之后尝试使用totalChips,但它似乎无法正常工作。我可以就此提出一些建议。

输出

<Blank File>

预期产出

Line1|password|500
Line2|password|600
//ModifiedLine can be either line based on UserName

代码在

之下
 public static void AddChips() {
      File oldFileName = new File("players.dat");
      File tmpFileName = new File("newplayers.dat");

      BufferedReader br = null;
      BufferedWriter bw = null;

      ArrayList<String> player = new ArrayList<String>();
      try {
         br = new BufferedReader(new FileReader(oldFileName));
         bw = new BufferedWriter(new FileWriter(tmpFileName));
         String line;
         Scanner read = new Scanner(System.in);
         System.out.println("Please Enter Username");
         String UserN = read.nextLine();
         System.out.println("Please Enter Chips to Add");
         String UserCadd = read.nextLine();

         while ((line = br.readLine()) != null) {
                String[] details = line.split("\\|");
                String Username = details[0];
                String Password = details[1];
                String Chips = details[2];
                int totalChips = (Integer.parseInt(UserCadd)+ Integer.parseInt(Chips));
            if (Username.equals(UserN))
               line = Username + "|" + Password + "|" + totalChips;
               bw.write("\r\n"+line);
         }

            bw.close();
            br.close();
            oldFileName.delete();
            tmpFileName.renameTo(oldFileName);
            AdminMenu();


      } catch (Exception e) {
         e.printStackTrace();
          return;
      } finally {
         try {
            if(br != null)
               br.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
         try {
            if(bw != null)
               bw.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }

}

新错误

java.lang.ArrayIndexOutOfBoundsException: 1
at testcode.AddChips(testcode.java:53)
at testcode.main(testcode.java:11)

0 个答案:

没有答案