package com.starain.io;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileOperation {
public static void main(String[] args) throws IOException {
File file1 = new File("D:\\hello4.txt");
File file2 = new File("D:\\hello4.txt");
if(file1.exists()){//判断file1文件是否存在
file1.delete();//删除file1文件
}
/*测试file1是否已经删除*/
if(file1.exists()){
System.out.println("file existed");
}else {
System.out.println("had been deleted");
}
/*如果file2不存在则创建file2,然后命名为test5.txt*/
if(!file2.exists()){
//抛出异常
try {
file2.createNewFile();//创建文件
System.out.println("文件已经创建");
} catch (IOException e) {
System.out.println("文件无法创建");
}
if(file2.isFile()){
//重命名
File name = new File("D:\\test5.txt");
file2.renameTo(name);
}
/*写文件*/
//FileWriter形式,不带缓冲,适合内容较少时
String pathName1 = "D:/test5.txt";
FileWriter filewriter1 = new FileWriter(pathName1);//可能抛出异常,所以用throw IOException或者try{}catch{}
filewriter1.write("This is a test program\n");
filewriter1.write("hello world");
filewriter1.close();//因为程序执行较快,但是文件读写较慢,
//不调用close()方法可能造成文件正在写时(未写完),程序执行完,写操作便终止,一些数据未写上去
//BufferedWriter高效的缓冲器流类
String pathName2 = "D:\\test6.txt";//文件不存在时自动创建,存在时覆盖旧文件
BufferedWriter filewriter2 = new BufferedWriter(new FileWriter(pathName2));
/*String pathName2 = "D:/test6.txt";
* FileWriter file1 = new FileWriter(pathName2);
* BufferedWriter filewriter2 = new BufferedWriter(file1);
*/
filewriter2.write("test6");
filewriter2.write("\nhello");//遇到非\n换行的系统导致不能正常换行
filewriter2.newLine();//newLine()方法换行,能解决不同系统间换行方法不同的难题
filewriter2.write("world");
filewriter2.close();//关闭流
}
}
}