How to make FileFilter in java?

后端 未结 9 2093
清歌不尽
清歌不尽 2020-12-05 02:07

like in title how to make filter to .txt files?

i wrote something like this but it has error :(

 private void jMenuItem1ActionPerformed(java.awt.even         


        
相关标签:
9条回答
  • 2020-12-05 02:47

    Another simple example:

    public static void listFilesInDirectory(String pathString) {
      // A local class (a class defined inside a block, here a method).
      class MyFilter implements FileFilter {
        @Override
        public boolean accept(File file) {
          return !file.isHidden() && file.getName().endsWith(".txt");
        }
      }
    
      File directory = new File(pathString);
      File[] files = directory.listFiles(new MyFilter());
    
      for (File fileLoop : files) {
        System.out.println(fileLoop.getName());
      }
    }
    
    // Call it
    listFilesInDirectory("C:\\Users\\John\\Documents\\zTemp");
    
    // Output
    Cool.txt
    RedditKinsey.txt
    ...
    
    0 讨论(0)
  • 2020-12-05 02:52
    File f = null;
    File[] paths;
    
    try {
    
        f = new File(dir);
    
        // filefilter
        FilenameFilter fileNameFilter = new FilenameFilter() {
    
            public boolean accept(File dir, String name) {
    
                if (name.lastIndexOf('.') > 0) {
    
                    int lastIndex = name.lastIndexOf('.');
                    String str = name.substring(lastIndex);
    
                    if (str.equals("." + selectlogtype)) {
                        return true;
                    }
                }
                return false;
            }
        };
    
        paths = f.listFiles(fileNameFilter);
    
        for (int i = 0; i < paths.length; i++) {
            try {
    
                FileWriter fileWriter = new FileWriter("C:/Users/maya02/workspace/ftp_log/filefilterlogtxt");
                PrintWriter bWriter = new PrintWriter(fileWriter);
    
                for (File writerpath1 : paths) {
                    bWriter.println(writerpath1);
                }
    
                bWriter.close();
            } 
            catch (IOException e) { System.out.println("HATA!!"); }
        }
        System.out.println("path dosyaya aktarıldı!.");
    } 
    catch (Exception e) { }
    
    0 讨论(0)
  • 2020-12-05 02:55

    Try something like this...

    String yourPath = "insert here your path..";
    File directory = new File(yourPath);
    String[] myFiles = directory.list(new FilenameFilter() {
        public boolean accept(File directory, String fileName) {
            return fileName.endsWith(".txt");
        }
    });
    
    0 讨论(0)
提交回复
热议问题