Reading and writing from and to the same file in Java

后端 未结 3 838
情话喂你
情话喂你 2021-02-20 03:58

I want to read from criteria.txt file, to tokenize and append at the end of the same file the tokens. The program throws an exception: No file found!

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-20 04:33

    You need to close your reader after you have finished reading the file i.e. after the while loop. Currently, you are closing it after reading the first line, which causes an "IOException: Stream closed" when it tries to read the second line.

    Change to:

    while((s=br.readLine())!=null)
    {
        strtok=new StringTokenizer(s," ");
        while(strtok.hasMoreTokens())
        {
            bw.write("\n"+strtok.nextToken());
        }
        //br.close(); <----- move this to outside the while loop
    }
    br.close();
    

提交回复
热议问题