1、文件
1.1、文件的概念
保存数据的地方。
1.2、文件流
文件在程序中是以流的形式来操作的。
流:数据在数据源(文件)和程序(内存)之间经历的路径。
输入流:数据从数据源(文件)到程序(内存)的路径。
输出流:数据从程序(内存)到数据源(文件)的路径。
1.3、创建文件
1.3.1创建文件对象相关构造器和方法
new File(String pathname) //根据路径构建个File对象。
new File(File parent, String child) //根据父目录文件+子路径构建。
new File(String parent,String child) //根据父目录+子路径构建。
createNewFile创建新文件。
1.3.2、应用实例FileCreate.java
请在D盘下,创建文件news1.txt、news2.txt、 news3.txt, 用三种不同方式创建。
public class FileCreate {
public static void main(String[] args) throws IOException {
//方式1
//注意细节: d:\I不能写成d,如果写成d表示在当前目录下
//创建文件news1.txt,可以测试
File file1 = new File("d:\\", "news1.txt");
if(file1.createNewFile()){
System.out.println("news1.txt创建成功!");
}else {
System.out.println("news1.txt创建失败!");
}
//方式2
///你也可以写成d:\news2.txt,第一个\表示转义符
File file2 = new File("d:/news2.txt");
if(file2.createNewFile()){
System.out.println("news2.txt创建成功!");
}else {
System.out.println("news2.txt创建失败!");
}
//方式3
File file = new File("d:\\");
File file3 = new File(file, "news3.txt");
if(file3.createNewFile()){
System.out.println("news3.txt创建成功!");
}else {
System.out.println("news3.txt创建失败!");
}
}
}
1.4、获取文件的相关信息
getName、getAbsolutePath, getParent、 length, exists、 isFile、
isDirectory
import org.junit.jupiter.api.Test;
import java.io.File;
public class FileInformation {
public static void main(String[] args) {
}
//获取文件相关信息
@Test
public void info(){
File file = new File("d:\\news1.txt");
String name = file.getName();
System.out.println("文件的名字:"+name);
String absolutePath = file.getAbsolutePath();
System.out.println("文件的绝对路径:"+absolutePath);
String parent = file.getParent();
System.out.println("文件的父级目录:"+parent);
long length = file.length();
System.out.println("文件的大小:"+length);//字节计算
boolean exists = file.exists();
System.out.println("文件是否存在:"+exists);
boolean file1 = file.isFile();
System.out.println("是否是一个标准文件:"+file1);
boolean directory = file.isDirectory();
System.out.println("是否是一个文件夹:"+directory);
}
}
1.5、目录操作
import java.io.File;
import java.io.IOException;
public class Directory_ {
public static void main(String[] args) throws IOException {
//1.删除指定文件
File file1 =new File("d:\\news1.txt");
if ((!file1.exists())) {
System.out.println("d:\\news1.txt不存在~");
}else{
if(file1.delete()){
System.out.println( "删除成功");
} else {
System.out.println("删除失败");
}
}
//2.delete只能删除空目录或者某个文件
File file2 =new File("D:l\\demo02");
if (!file2.exists()) {
System.out.println("D:\\demo02不存在");
}else{
if(file2.delete()){ //这个delete只能删除空目录或者某个文件
System.out.println("D:l\\demo02删除成功");
} else {
System.out.println("D:\\demo02删除失败~");
}}
//创建多级目录,创建单极目录使用mkdir
File file = new File("d:\\demo7\\a\\b\\c");
if(!file.exists()){
if(file.mkdirs()){
System.out.println("多级目录创建成功!");
}else {
System.out.println("多级目录创建失败!");
}
//创建news.txt
File sub = new File(file," news.txt");
if(sub.createNewFile()){
System.out.println("文件创建成功");
} else{
System.out.println("文件创建失败~");
}
}else {
System.out.println("d:\\demo7\\a\\b\\c目录已存在!");
}
}
}