转载 原文:https://blog.csdn.net/qq_26591517/article/details/80928746
判断文件或目录是否存在
判断File对象所指向的文件或者目录是否存在,使用exists()函数。
File f = new File("/Users/bemaster/Desktop/in.txt");
System.out.println(f.exists());
判断当前File对象是文件还是目录
判断当前File对象是否是文件,使用isFile()函数。
判断当前File对象是否是目录,使用isDirectory()函数。
File f = new File("/Users/bemaster/Desktop/in.txt");
File f2 = new File("/Users/bemaster/Desktop/in.txt");
if(f.isFile())
System.out.println("is file!!!");
if(f2.isDirectory())
System.out.println("is directory!!!");
新建文件或目录
新建文件,使用createNewFile()函数
File f = new File("/Users/bemaster/Desktop/in.txt");
try {
if(!f.exists())
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
新建目录,使用mkdir()或者mkdirs()函数。区别是前者是新建单级目录,而后者是新建多级目录。
即如果新建目录时,如果上一级目录不存在,那么mkdir()是不会执行成功的。
/*如果User目录,或者bemaster目录,或者Desktop目录不存在,
* 如果使用mkdir(),则新建tmp目录失败
* 如果使用mkdirs(),则连不存在的上级目录一起新建
*/
File f = new File("/Users/bemaster/Desktop/tmp");
if(!f.exists())
f.mkdir();
获取当前目录下的所有文件
list()函数返回当前目录下所有文件或者目录的名字(即相对路径)。
listFiles()函数返回当前目录下所有文件或者目录的File对象。
很显然,list()函数效率比较高,因为相比于listFiles()函数少了一步包装成File对象的步骤。
上面的两个函数都有另外一个版本,可以接受一个过滤器,即返回那么满足过滤器要求的。
public String[] list();
public String[] list(FilenameFilter filter);
public File[] listFiles();
public File[] listFiles(FileFilter filter);
public File[] listFiles(FilenameFilter filter);
删除文件或目录
删除文件或目录都是使用delete(),或者deleteOnExit()函数,但是如果目录不为空,则会删除失败。
delete()和deleteOnExit()的区别是前者立即删除,而后者是等待虚拟机退出时才删除。
File f = new File("/Users/bemaster/Desktop/in.txt");
f.delete();
如果想要删除非空的目录,则要写个函数递归删除。
/**
*
*<删除文件或者目录,如果目录不为空,则递归删除
* @param file filepath 你想删除的文件
* @throws FileNotFoundException 如果文件不存在,抛出异常
*
*/
public static void delete(File file) throws FileNotFoundException {
if(file.exists()){
File []fileList=null;
//如果是目录,则递归删除该目录下的所有东西
if(file.isDirectory() && (fileList=file.listFiles()).length!=0){
for(File f:fileList)
delete(f);
}
//现在可以当前目录或者文件了
file.delete();
}
else{
throw new FileNotFoundException(file.getAbsolutePath() + "is not exists!!!");
}
}
重命名(移动)文件或目录
重命名文件或目录是使用renameTo(File)函数,如果想要移动文件或者目录,只需要改变其路径就可以做到。
File f = new File("/Users/bemaster/Desktop/in.txt");
f.renameTo(new File("/Users/bemaster/Desktop/in2.txt"));
复制文件或目录
File类不提供拷贝文件或者对象的函数,所以需要自己实现。
/**
* through output write the byte data which read from input
* 将从input处读取的字节数据通过output写到文件
* @param input
* @param output
* @throws IOException
*/
private static void copyfile1(InputStream input, OutputStream output) {
byte[] buf = new byte[1024];
int len;
try {
while((len=input.read(buf))!=-1){
output.write(buf, 0, len);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally{
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void copyFile(String src, String des, boolean overlay) throws FileNotFoundException{
copyFile(new File(src), new File(des), overlay);
}
/**
*
* @param src 源文件
* @param des 目标文件
* @throws FileNotFoundException
*/
public static void copyFile(File src, File des, boolean overlay) throws FileNotFoundException {
FileInputStream fis = null;
FileOutputStream fos = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
if(src.exists()){
try {
fis = new FileInputStream(src);
bis = new BufferedInputStream(fis);
boolean canCopy = false;//是否能够写到des
if(!des.exists()){
des.createNewFile();
canCopy = true;
}
else if(overlay){
canCopy = true;
}
if(canCopy){
fos = new FileOutputStream(des);
bos = new BufferedOutputStream(fos);
copyfile1(bis, bos);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
throw new FileNotFoundException(src.getAbsolutePath()+" not found!!!");
}
}
public static void copyDirectory(String src, String des) throws FileNotFoundException{
copyDirectory(new File(src), new File(des));
}
public static void copyDirectory(File src, File des) throws FileNotFoundException{
if(src.exists()){
if(!des.exists()){
des.mkdirs();
}
File[] fileList = src.listFiles();
for(File file:fileList){
//如果是目录则递归处理
if(file.isDirectory()){
copyDirectory(file, new File(des.getAbsolutePath()+"/"+file.getName()));
}
else{
//如果是文件,则直接拷贝
copyFile(file, new File(des.getAbsolutePath()+"/"+file.getName()), true);
}
}
}
else{
throw new FileNotFoundException(src.getAbsolutePath()+" not found!!!");
}
}
获得当前File对象的绝对路径和名字
File f = new File("/Users/bemaster/Desktop/in.txt");
//输出绝对路径, 即/Users/bemaster/Desktop/in.txt
System.out.println(f.getAbsolutePath());
//输出父目录路径, 即/Users/bemaster/Desktop/
System.out.println(f.getParent());
//输出当然文件或者目录的名字, 即in.txt
System.out.println(f.getName());
统计文件或者目录大小
获得文件的大小可以使用length()函数。
File f = new File("/Users/bemaster/Desktop/in.txt");
System.out.println(f.length());
如果对目录使用length()函数,可能会返回错误的结果,所以只好自己写个函数递归统计其包含的文件的大小。
private static long getTotalLength1(File file){
long cnt = 0;
if(file.isDirectory()){
File[] filelist = file.listFiles();
for(File f : filelist){
cnt += getTotalLength1(f);
}
}
else{
cnt += file.length();
}
return cnt;
}
public static long getTotalLength(String filepath) throws FileNotFoundException{
return getTotalLength(new File(filepath));
}
public static long getTotalLength(File file) throws FileNotFoundException{
if(file.exists()){
return getTotalLength1(file);
}
else{
throw new FileNotFoundException(file.getAbsolutePath()+" not found!!!");
}
}
其它函数
File类所提供的函数当前不止这些,还有一些操作,比如获得文件是否可读,可写,可操作;设置文件可读,可写,可操作等等。
FileUtil工具类
下面是自己写的FileUtil工具类。
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
/**
*
* @author bemaster;
* @category 文件工具类,包含了基本的文件操作
* @version 1.0
*
*/
public class FileUtil {
private static final long B = 1;
private static final long K = B<<10;
private static final long M = K<<10;
private static final long G = M<<10;
private static final long T = G<<10;
/**
*
*删除文件或者目录,如果目录不为空,则递归删除
* @param filepath 你想删除的文件的路径
* @throws FileNotFoundException 如果该路径所对应的文件不存在,抛出异常
*
*/
public static void delete(String filepath) throws FileNotFoundException{
File file = new File(filepath);
delete(file);
}
/**
*
*<删除文件或者目录,如果目录不为空,则递归删除
* @param file filepath 你想删除的文件
* @throws FileNotFoundException 如果文件不存在,抛出异常
*
*/
public static void delete(File file) throws FileNotFoundException {
if(file.exists()){
File []fileList=null;
//如果是目录,则递归删除该目录下的所有东西
if(file.isDirectory() && (fileList=file.listFiles()).length!=0){
for(File f:fileList)
delete(f);
}
//现在可以当前目录或者文件了
file.delete();
}
else{
throw new FileNotFoundException(file.getAbsolutePath() + "is not exists!!!");
}
}
/**
* through output write the byte data which read from input
* 将从input处读取的字节数据通过output写到文件
* @param input
* @param output
* @throws IOException
*/
private static void copyfile1(InputStream input, OutputStream output) {
byte[] buf = new byte[1024];
int len;
try {
while((len=input.read(buf))!=-1){
output.write(buf, 0, len);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally{
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void copyFile(String src, String des, boolean overlay) throws FileNotFoundException{
copyFile(new File(src), new File(des), overlay);
}
/**
*
* @param src 源文件
* @param des 目标文件
* @throws FileNotFoundException
*/
public static void copyFile(File src, File des, boolean overlay) throws FileNotFoundException {
FileInputStream fis = null;
FileOutputStream fos = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
if(src.exists()){
try {
fis = new FileInputStream(src);
bis = new BufferedInputStream(fis);
boolean canCopy = false;//是否能够写到des
if(!des.exists()){
des.createNewFile();
canCopy = true;
}
else if(overlay){
canCopy = true;
}
if(canCopy){
fos = new FileOutputStream(des);
bos = new BufferedOutputStream(fos);
copyfile1(bis, bos);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
throw new FileNotFoundException(src.getAbsolutePath()+" not found!!!");
}
}
public static void copyDirectory(String src, String des) throws FileNotFoundException{
copyDirectory(new File(src), new File(des));
}
public static void copyDirectory(File src, File des) throws FileNotFoundException{
if(src.exists()){
if(!des.exists()){
des.mkdirs();
}
File[] fileList = src.listFiles();
for(File file:fileList){
//如果是目录则递归处理
if(file.isDirectory()){
copyDirectory(file, new File(des.getAbsolutePath()+"/"+file.getName()));
}
else{
//如果是文件,则直接拷贝
copyFile(file, new File(des.getAbsolutePath()+"/"+file.getName()), true);
}
}
}
else{
throw new FileNotFoundException(src.getAbsolutePath()+" not found!!!");
}
}
public static String toUnits(long length){
String sizeString = "";
if(length<0){
length = 0;
}
if(length>=T){
sizeString = sizeString + length / T + "T" ;
length %= T;
}
if(length>=G){
sizeString = sizeString + length / G + "G" ;
length %= G;
}
if(length>=M){
sizeString = sizeString + length / M + "M";
length %= M;
}
if(length>=K){
sizeString = sizeString + length / K+ "K";
length %= K;
}
if(length>=B){
sizeString = sizeString + length / B+ "B";
length %= B;
}
return sizeString;
}
private static long getTotalLength1(File file){
long cnt = 0;
if(file.isDirectory()){
File[] filelist = file.listFiles();
for(File f : filelist){
cnt += getTotalLength1(f);
}
}
else{
cnt += file.length();
}
return cnt;
}
public static long getTotalLength(String filepath) throws FileNotFoundException{
return getTotalLength(new File(filepath));
}
public static long getTotalLength(File file) throws FileNotFoundException{
if(file.exists()){
return getTotalLength1(file);
}
else{
throw new FileNotFoundException(file.getAbsolutePath()+" not found!!!");
}
}
}