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
61
62
63
64
65
66
67
68
69
70
71
72
|
package
com.yeqc.rwfile;
import
java.io.BufferedReader;
import
java.io.BufferedWriter;
import
java.io.File;
import
java.io.FileInputStream;
import
java.io.FileNotFoundException;
import
java.io.FileOutputStream;
import
java.io.IOException;
import
java.io.InputStreamReader;
import
java.io.OutputStreamWriter;
import
java.io.UnsupportedEncodingException;
public
class
ReadFile {
public
static
void
main(String[] args) {
File file =
new
File(
"text.txt"
);
if
(file.exists()) {
System.err.println(
"exist"
);
try
{
FileInputStream fis =
new
FileInputStream(file);
InputStreamReader isr =
new
InputStreamReader(fis,
"UTF-8"
);
BufferedReader br =
new
BufferedReader(isr);
String line;
while
((line = br.readLine()) !=
null
){
System.out.println(line);
}
br.close();
isr.close();
fis.close();
}
catch
(FileNotFoundException e) {
e.printStackTrace();
}
catch
(UnsupportedEncodingException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
}
try
{
File newfile =
new
File(
"newtext.txt"
);
FileOutputStream fos =
new
FileOutputStream(newfile);
OutputStreamWriter osw =
new
OutputStreamWriter(fos,
"UTF-8"
);
BufferedWriter bw =
new
BufferedWriter(osw);
bw.write(
"鹅\n"
);
bw.write(
"鹅鹅鹅\n"
);
bw.write(
"曲项向天歌\n"
);
bw.write(
"白毛浮绿水\n"
);
bw.write(
"红掌拨清波\n"
);
bw.close();
osw.close();
fos.close();
System.out.println(
"写入完成"
);
}
catch
(FileNotFoundException e) {
e.printStackTrace();
}
catch
(UnsupportedEncodingException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
}
}
|
运行结果:
1
2
3
4
5
6
7
|
exist
鹅
鹅鹅鹅
曲项向天歌
白毛浮绿水
红掌拨清波
写入完成
|
本文转自yeleven 51CTO博客,原文链接:http://blog.51cto.com/11317783/1769478