创建文件的三种方式
1.使用文件路径 new File(String pathName)
2.使用父文件目录 + 子文件目录 new File(File, String)
3.使用父文件路径 + 子文件路径
代码
import org.junit.Test;
import java.io.File;
import java.io.IOException;
public class FileCreate {
@Test
public void fileCreate1(){
String filepath = "d:\\news1.txt";
//String filepath = "d:\\a\\b\\c";
File file = new File(filepath);
if(file.exists()){
file.delete();
System.out.println(filepath + "已删除");
}else {
try {
//创建文件
file.createNewFile();
//创建文件夹
//file.mkdirs();
System.out.println(filepath + "已创建");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
System.out.println("文件路径:" + file.getPath());
System.out.println("字节数" + file.length());
}
@Test
public void fileCreate2(){
File parentFile = new File("d:\\");
String filepath = "news2.txt";
File file = new File(parentFile,filepath);
try {
file.createNewFile();
System.out.println("成功创建文件~");
} catch (IOException e) {
e.printStackTrace();
}
}
}