package file;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
public class FileCreat {
public static void main(String[] args) {
}
/**
* @Test注解:
* JUnit 4发布的新特性之一就是支持了@Test注解;
* @Test的使用 是该方法可以不用在main方法中调用就可以测试出运行结果的一种测试工具
* @throws IOException
*/
@Test
public void create1() throws IOException {
//方法1:完整路径
String filePath1 = "/Users/sabrina/Documents/为新工作冲鸭/test1.xlsx";
//方法2:父目录文件+子路径
File parentFile = new File("/Users/sabrina/Documents/为新工作冲鸭/");
String filePath2 = "test2.xlsx";
//方法3:父目录文件+子路径
String parentPath = "/Users/sabrina/Documents/为新工作冲鸭/";
String filePath3 = "test3.xlsx";
File myFile1 = new File(filePath1);
File myFile2 = new File(parentFile,filePath2);
File myFile3 = new File(parentPath,filePath3);
try {
// 创建文件,如果文件已经存在,这个方法会失败
if (myFile1.createNewFile()) {
System.out.println("文件创建成功: " + myFile1.getAbsolutePath());
} else {
System.out.println("文件已存在,无需创建。");
}
// 创建文件,如果文件已经存在,这个方法会失败
if (myFile2.createNewFile()) {
System.out.println("文件创建成功: " + myFile2.getAbsolutePath());
} else {
System.out.println("文件已存在,无需创建。");
}
// 创建文件,如果文件已经存在,这个方法会失败
if (myFile3.createNewFile()) {
System.out.println("文件创建成功: " + myFile3.getAbsolutePath());
} else {
System.out.println("文件已存在,无需创建。");
}
} catch (IOException e) {
// 异常处理
System.out.println("创建文件发生错误。"+e.getMessage());
e.printStackTrace();
}
}
}
MacOS使用Java创建新文件夹的方法
于 2024-03-24 15:12:33 首次发布