java目录文件夹操作

来源:互联网 发布:天刀脸型数据女萝莉 编辑:程序博客网 时间:2024/05/18 11:01


/**

* 拷贝一个目录或者文件到指定路径下

* @param source

* @param target

*/

public static void copy(File source, File target)

{

File tarpath = new File(target, source.getName());

if (source.isDirectory())

{

tarpath.mkdir();

File[] dir = source.listFiles();

for (int i = 0; i < dir.length; i++) { copy(dir[i], tarpath); } } else

{

try

{

InputStream is = new FileInputStream(source);

OutputStream os = new FileOutputStream(tarpath);

byte[] buf = new byte[1024];

int len = 0;

while ((len = is.read(buf)) != -1)

{

os.write(buf, 0, len);

}

is.close();

os.close();

}

catch (FileNotFoundException e)

{

e.printStackTrace();

}

catch (IOException e)

{

e.printStackTrace();

}

}

}

 

 

/**

* 列出某文件夹及其子文件夹下面的文件,并可根据扩展名过滤

*

* @param path

*/

public static void list(File path)

{

if (!path.exists())

{

System.out.println("文件名称不存在!");

}

else

{

if (path.isFile())

{

if (path.getName().toLowerCase().endsWith(".pdf")

|| path.getName().toLowerCase().endsWith(".doc")

|| path.getName().toLowerCase().endsWith(".html")

|| path.getName().toLowerCase().endsWith(".htm"))

{

System.out.println(path);

System.out.println(path.getName());

}

}

else

{

File[] files = path.listFiles();

for (int i = 0; i < files.length; i++)

{

list(files[i]);

}

}

}

}

 

 

 

package baidumapsdk.demo;

import java.io.File;

import java.util.ArrayList;

 

public class FileTest {

 private static ArrayList<String> filelist = new ArrayList<String>();

 

 public static void main(String[] args) throws Exception {

    

    String filePath = "E:/软件安装/开发环境/java/BaiduMap_AndroidSDK_v3.1.1_All/BaiduMap_AndroidSDK_v3.1.1_Sample/BaiduMapsApiDemo/src/baidumapsdk/demo";

    getFiles(filePath);

 }

 /*

  * 通过递归得到某一路径下所有的目录及其文件

  */

 static void getFiles(String filePath){

  File root = new File(filePath);

    File[] files = root.listFiles();

    for(File file:files){     

     if(file.isDirectory()){

      /*

       * 递归调用

       */

      getFiles(file.getAbsolutePath());

      filelist.add(file.getAbsolutePath());

      System.out.println("显示"+filePath+"下所有子目录及其文件"+file.getPath());//file.getAbsolutePath()

     }else{

      System.out.println("显示"+filePath+"下所有子目录"+file.getAbsolutePath());

     }     

    }

 }

}

 

 


0 0
原创粉丝点击