java读写文件

  • 读文件

    • FileInputStream
    • InputStreamReader
    • BufferedRead
      1
      2
      FileInputStream  fis = new FileInputStream(this.filePath)
      BufferedRead br = new BufferedReader(new InputStreamReader(fis, "UTF8"));
  • 写文件

    • FileOutputStream
    • OutputStreamWriter
      1
      2
      FileOutputStream fos = new FileOutputStream(this.filePath);
      OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF8");
  • 注意要关闭流,并且要按照从小到大顺序关闭流


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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package Test;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class {
private String filePath;
private StringBuffer sb;

public static void main(String[] args) {
FileOperation temp = new FileOperation("src/Test/text.txt");
temp.readFile();
temp.setFilePath("src/Test/test1.txt");
temp.writeFile();

}

public (String filePath) {
this.filePath = filePath;
this.sb = new StringBuffer();
}

public void readFile() {
FileInputStream fis = null;
BufferedReader br = null;

try {
fis = new FileInputStream(this.filePath);
br = new BufferedReader(new InputStreamReader(fis, "UTF8"));
int num = 0;
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
num++;
System.out.println(num + " " + line);
this.sb.append(line + "n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

public void writeFile() {
FileOutputStream fos = null;
OutputStreamWriter osw = null;

try {
fos = new FileOutputStream(this.filePath);
osw = new OutputStreamWriter(fos, "UTF8");
osw.write(this.sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
osw.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

public String getFilePath() {
return filePath;
}

public void setFilePath(String filePath) {
this.filePath = filePath;
}

public StringBuffer getSb() {
return sb;
}

public void setSb(StringBuffer sb) {
this.sb = sb;
}

}