设为首页 加入收藏

TOP

20个非常有用的Java程序片段(2)
2014-11-23 21:52:20 】 浏览:283
Tags:非常 有用 Java 程序 片段

  14. 列出文件和目录


  Java代码


  File dir = new File("directoryName");


  String[] children = dir.list();


  if (children == null) {


  // Either dir does not exist or is not a directory


  } else {


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


  // Get filename of file or directory


  String filename = children[i];


  }


  }


  // It is also possible to filter the list of returned files.


  // This example does not return any files that start with `.'.


  FilenameFilter filter = new FilenameFilter() {


  public boolean accept(File dir, String name) {


  return !name.startsWith(".");


  }


  };


  children = dir.list(filter);


  // The list of files can also be retrieved as File objects


  File[] files = dir.listFiles();


  // This filter only returns directories


  FileFilter fileFilter = new FileFilter() {


  public boolean accept(File file) {


  return file.isDirectory();


  }


  };


  files = dir.listFiles(fileFilter);


  15. 创建ZIP和JAR文件


  Java代码


  import java.util.zip.*;


  import java.io.*;


  public class ZipIt {


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


  if (args.length < 2) {


  System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");


  System.exit(-1);


  }


  File zipFile = new File(args[0]);


  if (zipFile.exists()) {


  System.err.println("Zip file already exists, please try another");


  System.exit(-2);


  }


  FileOutputStream fos = new FileOutputStream(zipFile);


  ZipOutputStream zos = new ZipOutputStream(fos);


  int bytesRead;


  byte[] buffer = new byte[1024];


  CRC32 crc = new CRC32();


  for (int i=1, n=args.length; i < n; i++) {


  String name = args[i];


  File file = new File(name);


  if (!file.exists()) {


  System.err.println("Skipping: " + name);


  continue;


  }


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Java常用异常与集合 下一篇利用Java查询Jar包内的驱动类名

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目