[英]Why doesn't my Java program write String into file?
I have two Threads and each Thread should write its name and an increasing number into a file - but it doesn't work. 我有两个线程,每个线程都应将其名称和一个递增的数字写入文件中-但它不起作用。
If i use the System.out.println()
method the threads are working perfectly only the writing into the file does fail. 如果我使用
System.out.println()
方法,则线程工作正常,只有写入文件确实失败。 Any idea why? 知道为什么吗?
This is how my Threads look like: 这是我的线程的样子:
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());
}
}
}
}
The main class looks like this: 主类如下所示:
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();
}
}
}
关闭文件后,立即立即将其打开,从而将其截断为零长度。
As Henry already pointed out, you essentially need to make your BufferedWriter shared between the threads so you don't constantly overwrite the file again. 正如Henry所指出的,本质上您需要使您的BufferedWriter在线程之间共享,这样您就不必再不断地覆盖文件了。
The following will do: 将执行以下操作:
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
}
}
}
The actual payload comes in a Runnable which goes here: 实际的有效负载位于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
}
}
}
}
Thanks guys :)! 多谢你们 :)!
I just added a true to the file location: 我刚刚在文件位置添加了true:
PrintWriter p2 = new PrintWriter(new FileWriter("C:\\Users\\User\\Desktop\\a1.txt",true));
And now java appends the text instead of overwriting the old one. 现在,java附加了文本,而不是覆盖旧文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.