简体   繁体   English

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

[英]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.

相关问题 我的 Java 程序没有在我的 .csv 文件中写入任何内容,即使没有“找不到文件”错误 - my Java program doesn't write anything in my .csv file, even though there is no "file not found" error 为什么我的Java程序不能正常工作? 它不允许我输入字符串语句小数位数。 - Why isn't my java program working?? It doesn't allow me to input my string statement scale. 为什么我的程序不将信息写入文件? - Why won't my program write information to the file? 为什么我的Selenium和Java基本程序无法正常工作? - Why doesn't my basic program through Selenium and Java works? 为什么我的代码没有写到文本文件? - Why doesn't my code write to a text file? 为什么我的程序不将数据写入文本文件? - Why doesn't my programme write data to a text file? 程序编译但未正确写入文件 - Program compiles but doesn't write to file correctly 为什么我的文件没有上传到我的Java Servlet? - Why doesn't my file get uploaded to my java servlet? 为什么在我的 Java 程序中导入文件不起作用? - Why won't the importing of a file work in my Java program? 为什么我的程序无法读取使用同一程序创建的文件? - Why doesn't my program read my file that was created using the same program?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM