本例以Windows, JDK1.7 为基础,这里使用BufferedWriter这个类来,对文件写入操作。
BufferedWriter 写入文件的操作,主要有以下方式:

1
2
3
4
5
6
void	write(int c);
void write(String s, int off, int len);
void write(char[] cbuf, int off, int len)

void write(char[] cbuf); //继承之Writer
void write(String str); //继承之Writer

更多关于BufferedWriter的用法可以参考API文档:http://docs.oracle.com/javase/7/docs/api/

文件写入代码:

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
package com.devnp.io;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriteBufferedWriter {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
write();
}

public static void write() throws IOException{
File file = new File("D:\\Person-Test\\1.txt");

BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));

String str = "Hi, Hello, I'm devnp.com" ;

bufferedWriter.write(str.toCharArray()); //写入整个char数组

bufferedWriter.write(65); //写入A

bufferedWriter.write(str.toCharArray(), 0, str.length()); //以char的方式写入,从0开始写入str的长度

bufferedWriter.write(str); //写入str

bufferedWriter.write(str, 0, str.length()); //写入str, 从第0个位置开始,连续学如str的长度

bufferedWriter.close();
}

}

查看写入文件的内容:
D:\Person-Test\1.txt

 Hi, Hello, I'm devnp.comAHi, Hello, I'm devnp.comHi, Hello, I'm devnp.comHi, Hello, I'm devnp.com