public static boolean checkFileWritingOn(String fileName) throws Exception{
long oldLen = 0;
long newLen = 0;
File file = new File(fileName);
while(true){
newLen = file.length();
if ((newLen - oldLen) > 0) {
oldLen = newLen;
System.out.println(file.length());
Thread.sleep(10000);
} else {
System.out.println("done");
return true;
}
}
}
{/collapse-item}
{collapse-item label="获取文件创建时间、最后更新时间等" open}
/**
* 获取文件的创建时间
* @param file
* @return
*/
public static Date getCreationTime(File file) throws IOException {
if (file == null) {
return null;
}else {
Path path = file.toPath();
BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
// 创建时间
Instant instant = attr.creationTime().toInstant();
Date fordate = Date.from(instant);
return fordate;
}
// 更新时间
//Instant instant = attr.lastModifiedTime().toInstant();
// 上次访问时间
//Instant instant = attr.lastAccessTime().toInstant();
//String format = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneId.systemDefault()).format(instant);
//return format;
}
{/collapse-item}
{collapse-item label="获取某路径下的所有文件/文件夹" open}
/**
* 获取路径下的所有文件/文件夹
* @param rootDir 需要遍历的文件夹路径
* @param isAddDirectory 是否将子文件夹的路径也添加到list集合中
* @return
*/
public static List<String> getAllFile(String rootDir, boolean isAddDirectory){
List<String> list = new ArrayList<String>();
File baseFile = new File(rootDir);
if (baseFile.isFile() || !baseFile.exists()) {
return list;
}
File[] files = baseFile.listFiles();
for (File file : files) {
if (file.isDirectory()) {
if(isAddDirectory){
list.add(file.getAbsolutePath());
}
list.addAll(getAllFile(file.getAbsolutePath(),isAddDirectory));
} else {
list.add(file.getAbsolutePath());
}
}
return list;
}
{/collapse-item}
{collapse-item label="复制文件到指定目录" open}
/**
* @param filePath
* @param targetPath
* @throws IOException
*/
public static void fileCope(String filePath, String targetPath) throws IOException {
//获得流
FileInputStream fileInputStream = new FileInputStream(filePath);
File targetFile = new File(targetPath);
//获取父目录
File parentFile = targetFile.getParentFile();
//判断是否存在
if (!parentFile.exists()) {
// 创建父目录文件夹
parentFile.mkdirs();
}
//判断文件是否存在
if (!targetFile.exists()) {
//创建文件
targetFile.createNewFile();
}
//新文件输出流
FileOutputStream fileOutputStream = new FileOutputStream (targetFile);
byte[] buffer= new byte[1024];
int len;
//将文件流信息读取文件缓存区,如果读取结果不为-1就代表文件没有读取完毕,反之已经读取完毕
while ((len=fileInputStream.read(buffer))!=-1) {
fileOutputStream.write(buffer, 0, len);
fileOutputStream.flush();
}
fileInputStream.close();
fileOutputStream.close();
}
{/collapse-item}
评论 (0)