Java文件IO

Java文件IO

按字符读写Reader、Writer

FileWrite、FileReader

FileWriter writer = new FileWriter(file, true)为追加写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static void main(String[] args) throws Exception {
String dir = "E:\\aaa.txt";
File file = new File(dir);
//如果文件不存在,创建文件
if (!file.exists())
file.createNewFile();
//创建FileWriter对象
FileWriter writer = new FileWriter(file);
//向文件中写入内容
writer.write("aaa");
writer.flush();
writer.close();

//创建FileReader对象,读取文件中的内容
FileReader reader = new FileReader(file);
char[] ch = new char[100];
reader.read(ch);
for (char c : ch) {
System.out.print(c);
}
System.out.println();
reader.close();
}

通过套一层BufferedWrite、BufferedReader,可以一行行来读

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void main(String[] args) throws Exception {
String dir = "E:\\aaa.txt";
File file = new File(dir);
//如果文件不存在,创建文件
if (!file.exists())
file.createNewFile();
//创建BufferedWriter对象
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
//向文件中写入内容
bw.write("aaa");
bw.flush();
bw.close();

//创建BufferedReader对象,读取文件中的内容
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println();
br.close();
}

按字节读写InputStream、OutputStream

FileOutputStream、FileInputStream

FileOutputStream fos = new FileOutputStream(file, true)为追加写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static void main(String[] args) throws Exception {
String dir = "E:\\aaa.txt";
File file = new File(dir);
//如果文件不存在,创建文件
if (!file.exists())
file.createNewFile();
//创建FileOutputStream对象,写入内容
FileOutputStream fos = new FileOutputStream(file);
//向文件中写入内容
fos.write("aaa".getBytes());
fos.close();

//创建FileInputStream对象,读取文件内容
FileInputStream fis = new FileInputStream(file);
byte[] bys = new byte[100];
while (fis.read(bys, 0, bys.length) != -1) {
//将字节数组转换为字符串
System.out.println(new String(bys));
}
fis.close();
}

Java文件IO
http://xwww12.github.io/2023/08/31/java/Java文件IO/
作者
xw
发布于
2023年8月31日
许可协议