用字符流实现每个文件夹中创建包含所有文件信息的readme.txt

时间:2021-12-01 06:39:32
 package com.readme;

 import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner; /**
* @author lisj
* 用字符流实现每个文件夹中创建包含所有文件信息的readme.txt
*
*/
public class FileNews { static int i=0; //定义文件个数全局变量
public static void main(String args[]) throws IOException{ find(); //调用查找文件函数
System.out.println("共有"+i+"个文件! "); } /**
* find()函数实现目录参数的传递
* 在此方法中调用写文件信息函数
*/
private static void find() throws IOException { Scanner scanner=new Scanner(System.in);
System.out.println("请输入目录(输入end退出程序):");
String findpath=scanner.next(); //输入路径 File file=new File(findpath); if(!file.exists()||!file.isDirectory()){ //判断该路径是否存在,是否是目录 if(findpath.equals("end")) //结束判断条件
{
System.out.println("程序结束,感谢使用!");
System.exit(-1);
}
else //输入错误,重新输入
{
System.out.println("输入的路径不存在,请重新输入!(输入end退出程序)");
find(); //递归调用
} } lookup(file); //调用判断文件,写文件信息函数 } /**
* lookup()函数实现目标目录下文件和文件夹的判别
* 在此方法中实现写入文件信息到readme.txt
*/
public static void lookup(File file) throws IOException{ String read=file.getAbsolutePath();
File readfileexist=new File(read+"/"+"readme.txt");
if(readfileexist.exists()){ //如果已经存在readme.txt,则删除
readfileexist.delete();
} File[] names=file.listFiles(); //输入的路径下的文件的目录 BufferedWriter out=null; //定义字符输出流 //查找到的文件属性数组的初始化
if(names!=null){ for(File name:names){ //遍历输入的路径下的文件和文件夹 if(name.isFile()) //判断该路径下是文件
{ //定义文件时间属性
Date date=new Date(name.lastModified());
SimpleDateFormat simpledate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String laststr = name.getParent();
File readfile=new File(laststr+"/"+"readme.txt"); //定义字符流写入的路径和文件名 out = new BufferedWriter(new FileWriter(readfile,true)); //定义字符流可追加写入信息 out.write("名字:"+name.getName()+" "); //写入文件信息
out.newLine();
out.write("大小:"+name.length()+" 字节");
out.newLine();
out.write("时间:"+simpledate.format(date)+" ");
out.newLine();
out.newLine();
out.flush(); //刷新缓冲以及关闭流
out.close();
i++; //统计文件个数 }
else
{
lookup(name);//递归调用函数
}
} } } }