创建文件相关构造器和方法
- 第一种:new File(String pathname)//根据文件路径构建一个File对象,(一个File对象代表一个文件)。
package com.elf.file;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
/**
* @author 45~
* @version 1.0
* 演示创建文件
*/
public class FileCreate {
public static void main(String[] args) {
}
//方式1:
@Test
public void create01(){
String filePath = "d:\\newwws1.txt";
File file = new File(filePath);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
e.printStackTrace();//把异常信息打出来
}
}
}
- 方式2:new File(File parent,String child) //根据父目录文件+子路径构建
- 方式3:new File(String parent,String child) //根据父目录+子路径构建
package com.elf.file;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
/**
* @author 45~
* @version 1.0
* 演示创建文件
*/
public class FileCreate {
public static void main(String[] args) {
}
//方式1:
@Test
public void create01(){
String filePath = "d:\\newwws1.txt";
File file = new File(filePath);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
e.printStackTrace();//把异常信息打出来
}
}
//方式2:new File(File parent,String child) //根据父目录文件+子路径构建
@Test
public void create02(){
File parentFile = new File("d://");
String filename = "newww2.txt";
File file = new File(parentFile, filename);
try {
file.createNewFile();
System.out.println("文件2创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
//方式3:new File(String parent,String child) //根据父目录+子路径构建
@Test
public void creat03(){
String parentPath = "d://";
String fileName = "news333.txt";
File file = new File(parentPath, fileName);
try {
file.createNewFile();
System.out.println("333创建成功~");
} catch (IOException e) {
e.printStackTrace();
}
}
}