import java.io.*;
public class Test2 {
public static void main(String[] args) {
// 建立一个文件写入流的空对象
BufferedWriter bufferedWriter = null;
try {
// 定义要读取的字符串
String str = "hello.world!";
// 定义计数器用于防止重复命名
int count = 0;
// 建立文件路径对象
File file = new File("d:" + File.separator + "readme.txt");
// 判断该文件是否存在
while (file.exists()) {
count++;
file = new File("d:" + File.separator + "readme(" + count
+ ").txt");
}
file.createNewFile();// 创建文件直到该文件名不重复
// 实例化一个BufferedWriter用于将字符流(字符串)写入到该文件中
bufferedWriter = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file)));
// 执行写入操作
bufferedWriter.write(str);
// 刷新缓冲
bufferedWriter.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 关闭流
try {
if (bufferedWriter != null)
bufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|