Java write to file. Using a loop

后端 未结 6 1689
不知归路
不知归路 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-25 01:32

    FileWriter file = new FileWriter("hello.txt");
        String sb =  " ";
    
       for (int i = 0; i < 1; i++) {
            sb += alphabet.charAt(r.nextInt(N));
            System.out.println(sb);
            int length = sb.length();
            file.write(sb);
            file.close();
            if(length == 30){
                sb = " ";
            }
        }
    

    You are initializing FileWriter once and closing it in the 1st iteration itself then trying to use it again in next iteration. Hence you are getting an Exception.

    I recommend put your for loop in try statement and close your FileWriter in finally statement. Here is oracle tut on try-catch-finally construct.

    Final code will go something like below

        FileWriter file = null;
        try {
            try {
                file = new FileWriter("hello.txt");
                String sb = " ";
                for (int i = 0; i < 1; i++) {
                    sb += alphabet.charAt(r.nextInt(N));
                    System.out.println(sb);
                    int length = sb.length();
                    file.write(sb);
                    if (length == 30) {
                        sb = " ";
                    }
                }
            } finally {
                file.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    

提交回复
热议问题