从/向同一文件写入和读取

时间:2011-12-26 15:31:34

标签: java multithreading io

是否可以同时读写同一文本文件?

第一个线程会将文本字符串添加到文件中,当没有数据时,它会添加“结束”字符串。

第二个线程应该读取该文件中的数据,并阻止是否有更多新数据。它应该在读取“结束”字符串时结束。

public class TheFileReader implements Runnable {


    public void run() {

        FileInputStream is = null;
        BufferedReader fbr = null;
        File file =  new File ("C:\\temp\\fileout3.txt");
        String s1 ="";

        try {       
            fbr = new BufferedReader(new FileReader(file), 1024*1024);

            while (s1.equals("exit")==false){
            s1 =fbr.readLine();
            if (s1==null){
                s1="";              
                Thread.sleep (50);
            }
            else
                System.out.println(s1);         
            }           

        } catch (IOException e) {           
            e.printStackTrace();
        } catch (InterruptedException e) {      
            e.printStackTrace();
        } finally
        {
            try {
                fbr.close();                        
            } catch (IOException e1) {

                e1.printStackTrace();
            }
        }

    }

public class TheFileWriter implements Runnable {

    public void run() {

        FileOutputStream os = null;
        BufferedWriter fbw = null;
        File file =  new File ("C:\\temp\\fileout3.txt");
        String s1 ="";

        try {       
            fbw = new BufferedWriter(new FileWriter(file), 1024*1024);
            for (int i = 0; i < 100; i++) {
                fbw.write("test" + i);
                fbw.newLine();
            }
            fbw.write("exit");

        } catch (IOException e) {           
            e.printStackTrace();
        } finally
        {
            try {
                fbw.close();                        
            } catch (IOException e1) {

                e1.printStackTrace();
            }
        }

    }
    }

更新:

如果我添加fbw.flush() after fbw.newLine();,我认为它会起作用。

2 个答案:

答案 0 :(得分:0)

不确定。你可以做一些像使用BlockingQueue作为你的中间人。轮询它直到某些东西,然后将其写入第二个线程中的文件。第一个线程只是在读取时将String对象弹出到队列中。

有很多复杂的方法可以做到这一点,但这是一种简单而又肮脏的方式。

答案 1 :(得分:0)

如果您确实想要使用文件进行协调,请使用同步方法将其作为第三方对象中存在的随机访问文件,例如

public synchronized String readWrite(boolean read, string writeStuff);

接受布尔运算符以确定是否要读取信息或写入信息。然后传递第二个字符串,其中包含您要写入的数据。如果您决定改为阅读,请使用返回值作为输出。