文件类的创建与删除
可以使用File类创建一个文件对象。通常使用三种构造方法来创建文件对象
File(String pathname)
定义File文件。
File file = new file("D:/1.txt)
File(String parent,String child)
File(File f,String child)
File file = new File("D:/mywork","word.txt");
如果D://mywork目录中没有word.txt文件,File类对象可通过调用createNewFile()方法来创建一个名称为word.txt的文件,如果word.txt文件存在,可以通过文件对象的delete()方法将其删除。
package IT.TEST.File;
import java.io.File;
import java.io.IOException;
public class example {
public static void main(String[] args) {
File file = new File("D:/example","work.txt");
if (file.exists()){
file.delete();
System.out.println("文件已删除");
}else{
try {
file.createNewFile();
System.out.println("文件已创建");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
获取文件信息
方法 | 说明 |
---|---|
getName() | 获取文件名称 |
canRead() | 判断文件是否可读 |
canWrite() | 判断文件是否可被写入 |
exists() | 判断文件是否存在 |
length() | 获取文件的长度 |
getAbsolutePath() | 获取文件的绝对路径 |
isFile() | 判断文件是否存在 |
isDirectory() | 判断是否是一个目录 |
isHidden() | 判断文件是否是隐藏文件 |
实例:
package IT.TEST.File;
/*
获取D盘中example文件夹下的work.txt文件名、文件长度,并判断该文件是否是隐藏文件。
*/
import java.io.File;
public class demo2 {
public static void main(String[] args) {
File file = new File("D:/example","work.txt");
if (file.exists()){
String name = file.getName();
long length = file.length();
boolean Hidden = file.isHidden();
System.out.println("文件的名称是: "+name);
System.out.println("文件的长度是: "+length);
System.out.println("文件是否是隐藏文件: "+Hidden);
}else{
System.out.println("文件不存在");
}
}
}
在JDK7中,多加了参数Path,使用该类来操作任何文件系统中的文件
创建文件对象:Path path = Paths.get("d:/1.txt")
创建文件
package IT.TEST.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Frist {
public static void main(String[] args) {
Path path = Paths.get("d://1.txt"); //创建path对象
try {
Path file = Files.createFile(path); //创建文件
System.out.println("文件创建成功!");
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件创建失败!");
}
}
}
删除文件
Files.delete(path); //文件删除方法
复制文件:将C盘的Stuff.txt文件复制到D盘MyStuff.txt文件
public static void main(String[] args){
Path source = Paths.get("C:\\Stuff.txt") //创建要进行复制的文件;
Path target = Paths.get("D:\\MyStuff.txt"); //创建复制后文件的保存地址
try{
Files.copy(source,target); //调用对文件进行复制的方法
}catch(IOException e){
e.printStackTrace();
}
}
移动文件
Files.move(Path source,Path target)