主类:

===============================================================================

package com.owe;

import com.utils.DeleteFile;

public class File {
//入口 以jar包的方式提供 外部传入路径 java - jar C:\Intel
public static void main(String[] args) {
if(args.length != 1)
{
System.out.println("请输入文件删除地址上级文件夹路径");
return;
}

String address = args[0];
DeleteFile deleteFile = new DeleteFile(address);
deleteFile.run();
}
}

=================================================================================

副类:

=================================================================================

package com.utils;

import java.io.File;


/**
* 定时删除文件夹下的文件
* @author xie
*
*/
public class DeleteFile extends Thread
{
//文件目录
private final String FILE_ADDRESS;

//构造函数
public DeleteFile(String address)
{
this.FILE_ADDRESS = address;
}

@Override
public void run()
{
while(true)
{
try {
traveseFolder(FILE_ADDRESS);
Thread.sleep(10000);
} catch (Exception e) {
// TODO: handle exception
}
}

}

/**
* 读取文件夹下的所有文件
* @param path
*/
public static void traveseFolder(String path)
{
File file = new File(path);
//如果存在该文件夹
if(file.exists())
{
File [] files = file.listFiles();
if(files.length == 0 )
{
System.out.println("该文件夹下没有文件!");
return;
}
else
{
for (File file2 : files)
{
//文件的路径
String filePath = file2.getAbsolutePath();
//如果文件夹下依旧是问价夹----递归
if(file2.isDirectory())
{
traveseFolder(filePath);
}
//是文件
else
{
//读取到文件路径
filePath = filePath.replace("\\", "/");
System.out.println("该文件夹下的文件路径为:"+filePath);
}
}
}
}
else
{
System.out.println("文件夹不存在!");
}
}

/**
* 删除以.log、.index、.timeindex结尾的文件
* @param filePath
*/
public static void deleteFileContainLogOrIndexOrTimeIndex(String filePath)
{
if(filePath.contains("."))
{
if(filePath.endsWith(".log") || filePath .endsWith(".index") || filePath.endsWith(".timeindex"))
{
System.out.println("=====================开始删除================");
deleteFile(filePath);
}
}
}

/**
* 删除文件
* @param path
*/
public static void deleteFile (String path)
{
File file = new File(path);
if(file.exists())
{
boolean success = true;
try
{
success = file.delete();
} catch (Exception e) {
success = false;
}
if(success)
{
System.out.println("删除文件"+file.getName()+"成功");
}
else
{
System.out.println("删除文件"+file.getName()+"失败");
}
}
}
}

 

posted on 2017-03-23 17:15  xiemingjin  阅读(232)  评论(0)    收藏  举报