文件基础知识和创建文件
1. 文件基础知识
什么是文件?
- 文件对我们来说并不陌生,文件是保存数据的地方,比如大家经常使用的word文档、text文件、excel文件...都是文件。它既可以保存照片,也可以保存视频、声音...
文件流
- 文件在程序中是以流的形式来操作的
2.创建文件
创建文件对象相关的构造器和方法
构造器
- new File(String pathname):根据路径构建一个File对象
- new File(String parent,String child):根据父目录+子路径构建一个File对象
- new File(File parent,String child):根据父目录文件+子路径构建一个File对象
方法
- createNewFile():创建新文件
演示创建文件
方式1:new File(String pathname)
public class FileCreate {
public static void main(String[] args) {
}
@Test
public void create01(){
String filePath = "d:\\news1.txt";
File file = new File(filePath);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
方式2:new File(String parent,String child)
public class FileCreate {
public static void main(String[] args) {
}
@Test
public void create02(){
String parentPath = "d:\\";
String filePath = "news2.txt";
File file = new File(parentPath,filePath);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
方式3:new File(File parent,String child)
public class FileCreate {
public static void main(String[] args) {
}
@Test
public void create02(){
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();
}
}
}