Java 612 - new File创建文件的几种方式
Java内置类java.io.File类提供了多种创建文章的方式,在本文里我们会介绍其中的几种外加代码演示。以下是File类提供的一些构造函数的介绍:File(String pathname):根据指定路径名创建File对象,路径名可以是相对路径或绝对路径。例如:File file = new File("example.txt");File(String parent, String child
前言
Java内置类java.io.File类提供了多种创建文章的方式,在本文里我们会介绍其中的几种外加代码演示。
以下是File类提供的一些构造函数的介绍:
-
File(String pathname):根据指定路径名创建File对象,路径名可以是相对路径或绝对路径。例如:File file = new File("example.txt");
-
File(String parent, String child):根据指定的父路径和子路径创建File对象。例如:File file = new File("C:\Users\Admin", "example.txt");
-
File(File parent, String child):根据指定的父文件和子路径名创建File对象。例如:File parent = new File("C:\Users\Admin"); File file = new File(parent, "example.txt");
-
File(URI uri):根据指定的URI创建File对象。例如:File file = new File(new URI("file:///C:/Users/Admin/example.txt"));
方式1, 根据pathname创建
File(String pathname):根据指定路径名创建File对象,路径名可以是相对路径或绝对路径。例如:File file = new File("example.txt");
@Test
public void create01(){
String filePath ="C:\\Users\\JinZh\\IdeaProjects\\TestJa\\software\\file01.txt";
File file = new File(filePath);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
方式2, 根据父路径+子路径创建
File(String parent, String child):根据指定的父路径和子路径创建File对象。例如:File file = new File("C:\Users\Admin", "example.txt");
@Test
public void create02(){
File ParentFile = new File("C:\\Users\\JinZh\\IdeaProjects\\TestJa\\software\\");
String fileName = "file02.txt";
File file = new File(ParentFile, fileName);
try {
file.createNewFile();
System.out.println("文件2创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
方式三,根据父目录文件+子路径创建
File(File parent, String child):根据指定的父文件和子路径名创建File对象。例如:File parent = new File("C:\Users\Admin"); File file = new File(parent, "example.txt");
@Test
public void create03(){
String parentPath = "C:\\Users\\JinZh\\IdeaProjects\\TestJa\\";
File parentFile = new File(parentPath);
String childPath = "software\\file003.txt";
File file = new File(parentFile, childPath);
try {
file.createNewFile();
System.out.println("文件3创建成功");
}catch (IOException e){
e.printStackTrace();
}
}
获取文件信息
File类里也有很多方法可以帮助我们获取文件信息。
@Test
public void info(){
File file = new File("C:\\Users\\JinZh\\IdeaProjects\\TestJa\\software\\file01.txt");
// 调用方法得到相应信息
System.out.println("文件名: "+file.getName());
System.out.println("文件绝对路径是: " + file.getAbsolutePath());
System.out.println("文件父级目录:" + file.getParent());
}
更多推荐
所有评论(0)