簡體   English   中英

寫入/讀取相同文件

[英]Writing and Reading from/to same file

是否可以同時讀寫同一文本文件?

第一個線程將文本字符串添加到文件,當沒有數據時它將添加“結尾”字符串。

第二個線程應從該文件讀取數據,並在有更多新數據時阻止。 當它讀取“結束”字符串時,它應該結束。

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();添加fbw.flush() after fbw.newLine(); 我認為它將起作用。

當然。 您可以做類似使用BlockingQueue的操作。 輪詢它,直到有東西存在,然后將其寫入第二個線程中的文件中。 當讀取對象時,第一個線程只是不斷將String對象彈出到隊列中。

有很多更復雜的方法可以做到這一點,但這是一種簡單而骯臟的方法。

如果您確實要使用文件進行協調,請使用同步方法將其設置為存在於第三方對象中的隨機訪問文件,例如

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

接受布爾運算符來確定您是要讀取信息還是寫入信息。 然后,傳遞第二個字符串以及您要寫入的數據。 如果決定改為讀取,則將返回值用作輸出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM