为什么我的Java程序没有将String写入文件?

时间:2016-01-28 19:13:26

标签: java multithreading file

我有两个线程,每个线程应该将其名称和一个递增的数字写入文件 - 但它不起作用。

如果我使用System.out.println()方法,线程工作正常,只有写入文件失败。知道为什么吗?

这就是我的主题的样子:

package ThreadTest;

import java.io.*;

public class Thread1 implements Runnable {

public void run() {
    int x = 0;
    while (true) {

        try {

            BufferedWriter p1 = new BufferedWriter(new FileWriter("C:\\Users\\User\\Desktop\\a1.txt"));
            x++;
            p1.write("Thread11: " + x);
            Thread.sleep(500);
            p1.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }
  }

}

主要类看起来像这样:

package ThreadTest;

public class ThreadTestTest {

    public static void main(String args[]) {

        try {
            Thread1 t11 = new Thread1();
            Thread t1 = new Thread(t11);

            Thread2 t22 = new Thread2();
            Thread t2 = new Thread(t22);

            t2.start();
            t1.start();

            t1. join();
             t2. join();


        } catch (Exception e) {
            e.getMessage();
        }

    }

}

3 个答案:

答案 0 :(得分:1)

关闭文件后,立即再次打开文件,从而将其截断为零长度。

答案 1 :(得分:0)

正如亨利已经指出的那样,你基本上需要让你的BufferedWriter在线程之间共享,这样你就不会再次覆盖文件。

以下是:

public class ThreadTest {
    public static void main(String[] args) {
        class ThreadSafeBufferedWriter extends BufferedWriter {
            public ThreadSafeBufferedWriter(Writer out) {
                super(out);     
            }

            @Override
            public synchronized void write(String str) throws IOException {
                super.write(str);
            }
        }

        try (BufferedWriter p1 = new ThreadSafeBufferedWriter(new FileWriter("/tmp/out.txt"))) {            
            Thread t1 = new Thread(new Payload("Thread1", p1));
            Thread t2 = new Thread(new Payload("Thread2", p1));         
            t2.start();
            t1.start();                
            t2.join();
            t1.join();                
        }
        catch (Exception e) {
            // do something smart
        }
    }
}

实际有效负载来自Runnable,其中包含:

class Payload implements Runnable {
    private String name;
    private Writer p1;

    public Payload(String _name, Writer _p1) {
        this.name = _name;
        this.p1 = _p1;
    }

    @Override
    public void run() {
        int x = 0;
        while (x < 10) { // you have to make sure these threads actually die at some point
            try {       
                x++;
                this.p1.write(this.name + ": " + x + "\n");
                Thread.sleep(500);      
            } catch (Exception e) {
                // do something smart
            }
        }
    }
}

答案 2 :(得分:0)

谢谢你们:)!

我刚刚在文件位置添加了一个true:

PrintWriter p2 = new PrintWriter(new FileWriter("C:\\Users\\User\\Desktop\\a1.txt",true));

现在java附加文本而不是覆盖旧文本。

相关问题