首页 > 技术文章 > //java递归调用输出一个目录下的所有子目录及文件名称 (最新增加)

ghostTao 2014-04-12 14:52 原文

 

//java递归调用输出一个目录下的所有子目录及文件名称
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class Test
{
public static void main(String[] args) throws IOException
{
Delete();
System.out.print("输入你选择的地址: ");
Scanner scan = new Scanner(System.in);
String filename = scan.next();
System.out.print("开始录入: ");
System.out.println("————————");
new Test().TreeName(filename, "");
System.out.println("总共访问的文件有: " + count);
}

private String listFileStr;
private static int count;

public void TreeName(String path, String tab) throws IOException
{
File file = new File(path);
File[] childFiles = file.listFiles();// 找出所有子目录
for (int i = 0; childFiles != null && i < childFiles.length; i++)
{
count++;
listFileStr = childFiles[i].getAbsolutePath() + "\n";// 隔行
System.out.println(tab
+ childFiles[i].getAbsolutePath());
filePrint(listFileStr);
if (childFiles[i].isDirectory())
{// 如果是目录的话,则调用自身
TreeName(childFiles[i].getPath(), tab + "\t");
}
}
}

private void filePrint(String str) throws IOException
{
byte[] buffer = str.getBytes();
// 通过字节数组来将控制台中写入的数据再次读入文件夹中
FileOutputStream outputStream = new FileOutputStream(
"Newoutput.doc", true);
// 定义FileOutputStream对象时增加了一个参数true
// 用于一行一行写入,防止覆盖上一行的内容
outputStream.write(buffer);
outputStream.close();
}

private static void Delete()
{
File file = new File("Newoutput.doc");// 文件名称
if (file.exists())
{
System.out.print("该文档存在" + '\t');
file.delete();
System.out.println("重新建立");
} else
{
System.out.println("该文档不存在,新建...");
try
{
file.createNewFile();// 文件新建操作
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}

推荐阅读