?1
package
?com.paiao.bdpm.flow.base;
?2
?3
import
?java.io.BufferedReader;
?4
import
?java.io.BufferedWriter;
?5
import
?java.io.File;
?6
import
?java.io.FileReader;
?7
import
?java.io.FileWriter;
?8
?9
public
?
class
?ReadTextFile?
{
10
????
public
?BufferedReader?bufread;
11
????
public
?BufferedWriter?bufwriter;
12
????File?writefile;
13
????String?filepath,?filecontent,?read;
14
????String?readStr?
=
?
""
;
15
????
//
從文本文件中讀取內容
16
????
public
?String?readfile(String?path)???
17
????
{
18
????????
try
?
{
19
????????????filepath?
=
?path;?
//
得到文本文件的路徑
20
????????????File?file?
=
?
new
?File(filepath);
21
????????????FileReader?fileread?
=
?
new
?FileReader(file);
22
????????????bufread?
=
?
new
?BufferedReader(fileread);
23
????????????
while
?((read?
=
?bufread.readLine())?
!=
?
null
)?
{
24
????????????????read?
=
?read
+
"
\r\n
"
;????????????
25
????????????????readStr?
=
?readStr?
+
?read;
26
????????????}
27
????????}
?
catch
?(Exception?d)?
{
28
????????????System.out.println(d.getMessage());
29
????????}
30
????????
return
?readStr;?
//
返回從文本文件中讀取內容
31
????}
32
33
????
//
向文本文件中寫入內容
34
????
public
?
void
?writefile(String?path,?String?content,?
boolean
?append)?
{
35
????????
try
?
{
36
????????????
boolean
?addStr?
=
?append;?
//
通過這個對象來判斷是否向文本文件中追加內容
37
????????????filepath?
=
?path;?
//
得到文本文件的路徑
38
????????????filecontent?
=
?content;?
//
需要寫入的內容
39
????????????writefile?
=
?
new
?File(filepath);
40
????????????
if
?(writefile.exists()?
==
?
false
)?
//
如果文本文件不存在則創建它?
41
????????????
{
42
????????????????writefile.createNewFile();
43
????????????????writefile?
=
?
new
?File(filepath);?
//
重新實例化
44
????????????}
45
????????????FileWriter?filewriter?
=
?
new
?FileWriter(writefile,?addStr);
46
????????????
//
刪除原有文件的內容
47
????????????java.io.RandomAccessFile?file
=
?
new
?java.io.RandomAccessFile(path,
"
rw
"
);
48
????????????file.setLength(
0
);
49
????????????
//
寫入新的文件內容
50
????????????filewriter.write(filecontent);
51
????????????filewriter.close();
52
????????????filewriter.flush();
53
????????}
?
catch
?(Exception?d)?
{
54
????????????System.out.println(d.getMessage());
55
????????}
56
????}
57
58
????
public
?
static
?
void
?main(String[]?args)?
throws
?Exception?
{
59
????????ReadTextFile?parse?
=
?
new
?ReadTextFile();
60
????????String?filecontent?
=
?parse.readfile(
"
c:/applicationContext.xml
"
);????????
61
????????parse.writefile(
"
c:/applicationContext.xml
"
,filecontent,
true
);
62
????????
63
????}
64
}

?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

61

62

63

64
