约 300 字 预计阅读 2 分钟
字符流-写出数据
字符流写数据
步骤:
- 创建字符输出流对象
| Constructor |
描述 |
FileWriter(File file) |
给一个File对象构造一个FileWriter对象。 |
| FileWriter(FileDescriptor fd) |
构造与文件描述符关联的FileWriter对象。 |
| FileWriter(File file, boolean append) |
给一个File对象构造一个FileWriter对象。 |
FileWriter(String fileName) |
构造一个给定文件名的FileWriter对象。 |
| FileWriter(String fileName, boolean append) |
构造一个FileWriter对象,给出一个带有布尔值的文件名,表示是否附加写入的数据。 |
- 写数据
| 方法名 |
说明 |
| void write(int c) |
写一个字符 |
| void write(char[] cbuf) |
写出一个字符数组 |
| void write(char[] cbuf, int off, int len) |
写出字符数组的一部分 |
| void write(String str) |
写一个字符串 |
| void write(String str, int off, int len) |
写一个字符串的一部分 |
- 释放资源
写一个字符
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public static void main(String[] args){
//创建字符输出流的对象
//FileWriter fw = new FileWriter(new File("charstream\\a.txt"));
FileWriter fw = new FileWriter("charstream\\a.txt");
//写出数据
fw.write(97); //a
fw.write(98); //b
fw.write(99); //c
//释放资源
fw.close();
}
|
写一个字符数组
1
2
3
4
5
6
7
8
9
10
11
12
|
public static void main(String[] args){
//创建字符输出流的对象
//FileWriter fw = new FileWriter(new File("charstream\\a.txt"));
FileWriter fw = new FileWriter("charstream\\a.txt");
//写出数据
char[] chars = {97, 98, 99, 100, 101};
fw.write(chars);
//释放资源
fw.close();
}
|
写出字符数组的一部分
1
2
3
4
5
6
7
8
9
10
11
12
|
public static void main(String[] args){
//创建字符输出流的对象
//FileWriter fw = new FileWriter(new File("charstream\\a.txt"));
FileWriter fw = new FileWriter("charstream\\a.txt");
//写出数据
char[] chars = {97, 98, 99, 100, 101};
fw.write(chars, 0, 3); //abc
//释放资源
fw.close();
}
|
写一个字符串
1
2
3
4
5
6
7
8
9
10
11
12
|
public static void main(String[] args){
//创建字符输出流的对象
//FileWriter fw = new FileWriter(new File("charstream\\a.txt"));
FileWriter fw = new FileWriter("charstream\\a.txt");
//写出数据
String line = "程序员abc";
fw.write(line);
//释放资源
fw.close();
}
|
写一个字符串的一部分
1
2
3
4
5
6
7
8
9
10
11
12
|
public static void main(String[] args){
//创建字符输出流的对象
//FileWriter fw = new FileWriter(new File("charstream\\a.txt"));
FileWriter fw = new FileWriter("charstream\\a.txt");
//写出数据
String line = "程序员abc";
fw.write(line, 0, 2); //程序
//释放资源
fw.close();
}
|