今天在写一个linux的java守护进程的时候,无意间就用到了java同时读写的功能。
看错误代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60 |
package
cn.sunchuanzhen.main; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public
class DomainDemo { /** * @param args * @throws IOException */ public
static void main(String[] args) throws
IOException { File file = new
File( "C:/ax.txt" ); if (!file.exists()){ try
{ file.createNewFile(); } catch
(IOException e) { e.printStackTrace(); throw
new RuntimeException( "文件创建失败" ); } } while
( true ) { FileWriter fw = new
FileWriter(file); BufferedWriter bfw = new
BufferedWriter(fw); FileReader fr = new
FileReader(file); BufferedReader bfr = new
BufferedReader(fr); String str = null ; StringBuilder sb = new
StringBuilder(); String buf = null ; // System.out.println(bfr.readLine()); while ((buf = bfr.readLine())!= null ) { sb.append(buf); } str = System.currentTimeMillis()+ "" +sb.toString(); System.out.println(str); bfw.write(str); bfw.newLine(); bfw.flush(); fw.close(); fr.close(); bfw.close(); bfr.close(); try
{ Thread.sleep( 5 * 1000 ); } catch
(InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } |
在上述的代码当中,读写同时进行没有先后顺序。这样导致的结果就是readLine()出来的内容是null,也就是同时读写的一个弊病。
经别人指正后修改如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60 |
package
cn.sunchuanzhen.main; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public
class DomainDemo { /** * @param args * @throws IOException */ public
static void main(String[] args) throws
IOException { File file = new
File( "C:/ax.txt" ); if (!file.exists()){ try
{ file.createNewFile(); } catch
(IOException e) { e.printStackTrace(); throw
new RuntimeException( "文件创建失败" ); } } while
( true ) { FileReader fr = new
FileReader(file); BufferedReader bfr = new
BufferedReader(fr); String str = null ; StringBuilder sb = new
StringBuilder(); String buf = null ; // System.out.println(bfr.readLine()); while ((buf = bfr.readLine())!= null ) { sb.append(buf+ "\r\n" ); } str = System.currentTimeMillis()+ "" +sb.toString(); fr.close(); bfr.close(); FileWriter fw = new
FileWriter(file); BufferedWriter bfw = new
BufferedWriter(fw); bfw.newLine(); bfw.write(str); bfw.newLine(); bfw.flush(); fw.close(); bfw.close(); try
{ Thread.sleep( 5 * 1000 ); } catch
(InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } |
这时候就工作了,操作完了读操作后,然后把读操作关闭,之后再进行写操作,这个样子就不会有错了。
原文:http://www.cnblogs.com/sunchuanzhen/p/readLine.html