Zisis Kostakakis
Zisis Kostakakis

Reputation: 86

Filter out the text files

The code separates files from directories.

I am trying to filter out the text files(.txt) and print out the files that remain.

I don't want the text files to be printed at all. I want the code to be implemented after the if statement if (listOfFiles[i].isFile()) { so after it checks to see if a given value is an actual file and then to determine if it is a text file, and if either test fails, add it to the listOfFiles array list.

Need help

import java.io.BufferedInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Exc_3 {

    public static void main(String[] args) {
        File folder = new File("C:\\Users\\skyla\\Desktop");
        File[] listOfFiles = folder.listFiles();
        List<String> files = new ArrayList<>();
        List<String> directories = new ArrayList<>();

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

            if (listOfFiles[i].isFile()) {
                    files.add(listOfFiles[i].getName());
            } else if (listOfFiles[i].isDirectory()) {
                directories.add(listOfFiles[i].getName());
            }
        }
        System.out.println("List of files :\n---------------");
        for (String fName : files)
            System.out.println(fName);

        System.out.println("\nList of directories :\n---------------------");
        for (String dName : directories)
            System.out.println(dName);
    }
}

Upvotes: 0

Views: 326

Answers (2)

NomadMaker
NomadMaker

Reputation: 448

Since you're only checking if the file extension is ".txt" then you can check the name with String.endsWith(".txt")

if (listOfFiles[i].isFile()) {
   if (listOfFiles[i].getName().endsWith(".txt")) {
      files.add(listOfFiles[i].getName());
   }
}

Upvotes: 1

NaSo91
NaSo91

Reputation: 1

Why don't you use the piece of code below. You can also use it into a function that checks whether your files is a .txt file by producing a boolean true if mimeType="text/plain"

Path path = FileSystems.getDefault().getPath("myFolder", "myFile");
String mimeType = Files.probeContentType(path);

Good luck

Upvotes: 0

Related Questions