如何从一个文件夹中单独获取.png文件

时间:2013-10-31 18:40:04

标签: java file include png directory

实际上,我正在尝试压缩一个文件夹中的所有文件。来自其他文件夹的.png文件。我可以从一个文件夹中获取所有文件。但我无法从java中的另一个文件夹中获取.png文件。有什么办法吗?

代码:

public class Zip {
    public static void zip(String filepath,String reportFileName){
        try {
            File inFolder=new File(filepath);
            File inFolder1=new File("../Agent_Portal_Auto_Testing/ReportCharts");
            File outFolder=new File(reportFileName);
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFolder)));
            BufferedInputStream in = null;
            byte[] data  = new byte[1000];
            String files[] = inFolder.list();
            String files1[]=inFolder1.list();
            for (int i=0; i<files.length; i++) {
                in = new BufferedInputStream(new FileInputStream
                        (inFolder.getPath() + "/" + files[i]), 1000);  
                out.putNextEntry(new ZipEntry(files[i])); 
                int count;
                while((count = in.read(data,0,1000)) != -1) {
                    out.write(data, 0, count);
                }
            }

            for (int i=0; i<files1.length; i++) {
                in = new BufferedInputStream(new FileInputStream
                        (inFolder1.getPath() + "/" + files1[i]), 1000);  
                out.putNextEntry(new ZipEntry(files1[i])); 
                int count;
                while((count = in.read(data,0,1000)) != -1) {
                    out.write(data, 0, count);
                }
            }
            out.closeEntry();
            out.flush();
            out.close();

        }
        catch(Exception e) {
            e.printStackTrace();
        } 
    }   
}

在上面的代码中,我从ReportCharts文件夹中获取所有文件。但我只需要获取.png文件。

2 个答案:

答案 0 :(得分:3)

请参阅http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles(java.io.FileFilter)

您可以使用文件过滤器仅过滤出PNG文件

http://docs.oracle.com/javase/7/docs/api/java/io/FileFilter.html

 File [] pngFiles = directory.listFiles(new FileFilter() {
     public boolean accept(File file) {
         return file.isFile() && file.getName().toLowerCase().endsWith(".png");
     }
 });

答案 1 :(得分:0)

如果您的文件是.png,则可以添加验证:

if (files1[i].contains(".png"))

for循环中