本次博客带领大家了解IO流中文件的用法,了解文件的定义,文件的创建方式等等。
一、文件
- 文件,对我们并不陌生,文件是保存数据的地方,比如大家经常使用的word文档,txt文档,excel文件等等都是文件。它既可以保存一张图片,也可以保存视频,声音等等。
二、文件流
- 文件在程序中是以流的形式来操作的。
- 流:数据在数据源(文件)和程序(内存)之间经历的路径。
- 输入流:数据从数据源(文件)到程序(内存)的路径。
- 输出流:数据从程序(内存)到数据源(文件)的路径。
三、常用的文件操作
-
创建文件对象相关构造器和方法
-
相关方法
-
new File(String pathname)//根据路径构建一个File对象
-
new File(File parent,String child)//根据父目录文件+子路径构建
-
new File(String parent,String child)//根据父目录+子路径构建
-
createNewFile 创建新文件
-
//方式1 new File(String pathname)
@Test
public void create01(){
String filePath = "d:\\111\\new1.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:\\111\\");
String fileName = "news2.txt";
//这里的file对象,在java程序中,只是一个对象。
//只有执行了createNewFile 方法,才会真正的,在磁盘创建文件。
File file = new File(parentfile,fileName);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
//方式3 new File(String parent,String child)//根据父目录+子路径构建
@Test
public void create03(){
String parentPath = "d:\\111\\";
String fileName = "news3.ext";
File file = new File(parentPath,fileName);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 获取文件的相关信息
public void info(){
//先创建文件对象
File file = new File("d:\\111\\new1.txt");
//调用相应的方法,得到对应信息
System.out.println("文件名字="+ file.getName());
System.out.println("文件绝对路径="+ file.getAbsolutePath());
System.out.println("文件父级目录="+ file.getParent());
System.out.println("文件大小(字节)="+ file.length());
System.out.println("文件是否存在="+ file.exists());
System.out.println("是不是一个文件="+ file.isFile());
System.out.println("是不是一个目录="+ file.isDirectory());
}
- 目录的操作和文件删除
- mkdir创建一级目录、mkdirs创建多级目录、delete删除空目录或文件。
//判断 d:\\111\\new1.txt 是否存在,若果存在就删除
@Test
public void m1(){
String filePath = "d:\\111\\new1.txt";
File file = new File(filePath);
if(file.exists()){
if(file.delete()){
System.out.println(filePath + "删除成功");
}else{
System.out.println(filePath + "删除失败");
}
} else {
System.out.println("该文件不存在...");
}
}
//判断 d:\\111\\demo02 是否存在,若果存在就删除,否则提示不存在
//这里我们需要体会到,在java编程中,目录也被当做文件。
@Test
public void m2(){
String filePath = "d:\\111\\demo02";
File file = new File(filePath);
if(file.exists()){
if(file.delete()){
System.out.println(filePath + "删除成功");
}else{
System.out.println(filePath + "删除失败");
}
} else {
System.out.println("该目录不存在...");
}
}
//判断 D:\\111\\a\\b\\c 目录是否存在,如果存在就提示已经存在,否则就创建
@Test
public void m3(){
String directoryPath = "d:\\111\\demo\\a\\b\\c";
File file = new File(directoryPath);
if(file.exists()){
System.out.println(directoryPath + "存在...");
} else {
if(file.mkdirs()){
System.out.println(directoryPath + "创建成功..");
} else {
System.out.println(directoryPath + "创建失败...");
}
}
}