Java write to file. Using a loop

后端 未结 6 1687
不知归路
不知归路 2021-01-25 00:53

I have a simple application that yet would trash a text file (it\'s just practice) I\'m only 3 days with Java yet. Problem is there are no errors until you run the program then

6条回答
  •  借酒劲吻你
    2021-01-25 01:47

    The problem is that you are closing your FileWriter and trying to use it again.

    Instead, close the writer after you've finished the loop:

    try (FileWriter file = new FileWriter("hello.txt")) {
      String sb = " ";
      for (int i = 0; i < 1; i++) {  // Note: added a i++
        sb += alphabet.charAt(r.nextInt(N));
        System.out.println(sb);
        int length = sb.length();
        file.write(sb);
        // file.close();   <---- NOPE: don't do this
        if (length == 30) {
          sb = " ";
        }
      }
    }
    

    Thanks to Andrew for spotting the i++ omission.

提交回复
热议问题