Java多程序写在同一文本文件上

时间:2016-06-10 15:51:52

标签: java

我有两个单独的程序NumberWriter.java将少量数字写入log.txt文件,CharWriter.java将少量数字写入log.txt文件。如果我同时运行两个程序(几乎同时从两个不同的控制台运行),那么没有错误或异常,即两个都运行成功。然后我希望在log.txt文件中获取数字和字符的文件内容混合但是只获得数字或字符。

我完全没有发现问题。任何帮助将不胜感激。

NumberWriter.java

import java.io.IOException;
import java.io.FileWriter;
import java.lang.Exception;

public class NumberWriter {
    public static void main(String args[]) throws IOException, Exception{
        FileWriter fw = new FileWriter("log.txt");
        for (int i = 01; i < 10; i++)  {
            fw.append(String.valueOf(i) + "\r\n");
            System.out.println("NumberWriter: " + i);
            Thread.sleep(1000);
        }
        fw.close();
        System.out.println("number write done!");
    }
}

CharWriter.java

import java.io.IOException;
import java.io.FileWriter;
import java.lang.Exception;

public class CharWriter {
    public static void main(String args[]) throws IOException, Exception{
        FileWriter fw = new FileWriter("log.txt");
        String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        for (int i = 01; i < 10; i++)  {
            fw.append(s.charAt(i) + "\r\n");
            System.out.println("CharWriter: " + s.charAt(i));
            Thread.sleep(1000);
        }
        fw.close();
        System.out.println("char write done!");
    }
} 
同时运行两个程序后

log.txt 文件内容

或者

B
C
D
E
F
G
H
I
J

1
2
3
4
5
6
7
8
9

编辑:两个程序都运行无异常和错误所以我期待混合字符和数字。什么是我的理解滞后。

enter image description here

3 个答案:

答案 0 :(得分:3)

没有错误。

所有现代操作系统都有文件系统写锁定,因此任何时候只有一个人/程序可以写入该文件。如果你进行一些调查,你会发现当你同时运行时,一个会因IOException而失败

答案 1 :(得分:1)

It is not clear what happens. Both Java and the OS buffer the output so it is unlikely you would ever see interleaved output. You are writing only 10 bytes, which will be buffered in memory and not actually written until the file is closed.

This is an area where the behavior depends on the interactions of multiple moving parts (your program, the Java I/O system, the OS) and without file locking the behavior is non-deterministic.

I suggest you modify your code as follows:

  1. Write 10000 lines in each program instead of 10
  2. Add a 10ms delay inside the loop so both programs take 100 seconds to run
  3. Flush the output on each iteration

This will cause actual overlap and let you determine what happens.

答案 2 :(得分:0)

可能更接近您正在寻找的是使用服务器/客户端系统写入共享的JTextArea,然后将其写入文本文件