Lavinia Lavinia - 4 months ago 18
Java Question

Reading and writing from and to the same file in Java

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!
I do not know where my mistake is. Any suggestion would help me. Thank you in advance!

Here is my code:

import java.io.*;
import java.util.StringTokenizer;

public class Test
{
private FileReader fr;
private BufferedReader br;
private FileWriter fw;
private BufferedWriter bw;
private StringTokenizer strtok;
private String s;

//constructor
public Test()
{
try
{
fw=new FileWriter("criteria.txt", true);
bw=new BufferedWriter(fw);

try
{
fr=new FileReader("criteria.txt");
br=new BufferedReader(fr);

while((s=br.readLine())!=null)
{
strtok=new StringTokenizer(s," ");
while(strtok.hasMoreTokens())
{
bw.write("\n"+strtok.nextToken());
}
br.close();
}
}
catch(FileNotFoundException e)
{
System.out.println("File was not found!");
}
catch(IOException e)
{
System.out.println("No file found!");
}

bw.close();
}
catch(FileNotFoundException e)
{
System.out.println("Error1!");
}
catch(IOException e)
{
System.out.println("Error2!");
}
}

public static void main(String[] args)
{
Test t=new Test();
}
}

Answer

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();
Comments