Lavinia
Lavinia

Reputation: 263

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

Upvotes: 13

Views: 46806

Answers (4)

Yura
Yura

Reputation: 1823

you can use RandomAccessFile - it can read, write same file same time as seeking and getting current cursor position

Upvotes: 0

Morufu Salawu
Morufu Salawu

Reputation: 185

Your greatest undoing is placing the br.close(); inside the while() loop: You are telling the computer each time it writes to the file to close it immediately, hence the file remained closed and computer will never find it during the next iteration/ execution of the loop. However, I have edit the initial program to this:

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

The folder or directory the file exist doesn't matter in this case as the program will create a new file named "criteria.txt" in the same folder as the java program; however, you will have to open the file with a text editor to add/ append some data as the file will be blank initially. Subsequent run of the program will now append the already inserted content(s) as a concatenation string on a new line. A new line will be produced each time the program is run. Hope this helps.

Upvotes: 2

Dranste
Dranste

Reputation: 86

In my opinion you can't do that. You can't open the same file to read and write at the same time. You have to open and save the file information in a data structure and then close it. Then you have to work with the data structure in memory and open the file to write results. And when you finish to write you should close it.

Upvotes: -1

dogbane
dogbane

Reputation: 274838

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

Upvotes: 8

Related Questions