How Can I Count Files By File Type? - Java - Stack Overflow

    1. Home
    2. Questions
    3. Tags
    4. Users
    5. Companies
    6. Jobs
    7. Discussions
    8. Collectives
    9. Communities for your favorite technologies. Explore all Collectives

  1. Teams

    Ask questions, find answers and collaborate at work with Stack Overflow for Teams.

    Try Teams for free Explore Teams
  2. Teams
  3. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams How can I count files by file type? Ask Question Asked 2 years, 8 months ago Modified 2 years, 8 months ago Viewed 1k times 1

I have a Java program that goes over all the folders and files inside a given folder and it prints them. The issues is that now I want to count all the files in the folder by their extension. How can I do that?

This is my code so far:

package ut5_3; import java.io.File; import java.util.ArrayList; import org.apache.commons.io.FilenameUtils; public class UT5_3 { ArrayList<String> extensionArray = new ArrayList<String>(); ArrayList<String> extensionArrayTemp = new ArrayList<String>(); public static void main(String[] args) { File directoryPath = new File("C://Users//Anima//Downloads//MiDir"); File[] directoryContent = directoryPath.listFiles(); UT5_3 prueba = new UT5_3(); prueba.goOverDirectory(directoryContent); } public void goOverDirectory(File[] directoryContent) { for (File content : directoryContent) { if (content.isDirectory()) { System.out.println("==========================================="); System.out.println("+" + content.getName()); goOverDirectory(content.listFiles()); // Calls same method again. } else { String directoryName = content.getName(); System.out.println(" -" + directoryName); String fileExtension = FilenameUtils.getExtension(directoryName); } } } }

So far I've tried making two ArrayList. One to store all the extensions from all the files and another one to store the distinct extensions, but I got really confused and I didn't know how to continue with that idea.

If it is too complex, it'd be great if you could explain an easier way to do it too. Thanks!

Share Improve this question Follow asked Mar 22, 2022 at 23:23 DaniC's user avatar DaniCDaniC 112 bronze badges 3
  • How comprehensive is this? Do you need a separate count of files by extension in each folder and subfolder, or do you want a general count of files by extension? – hfontanez Commented Mar 23, 2022 at 0:13
  • I posted a solution that I think will for you. Need to run on Java 8 or higher because it uses the Stream API. – hfontanez Commented Mar 23, 2022 at 1:03
  • Just a general count of files by extensions, yes. And well, the solution looks great, tho I'm a begginer so I'm not familiar at all wish streams, maps, collectors... But I'll work my way up there, ty ^^ – DaniC Commented Mar 23, 2022 at 1:23
Add a comment |

2 Answers 2

Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 2

So if I understand you correctly, you want to store the count of all of the file extensions you see. Here is how I would approach it.

First initialize a map with a String as the key and int as the value, at the top of your class like so.

private HashMap<String, Integer> extensions = new HashMap<String, Integer>();

Then you can run this whenever you need to add an extension to the count.

String in = "exe"; if(extensions.containsKey(in)) extensions.put(in, extensions.get(in) + 1); else extensions.put(in, 1);

If you want to retrieve the count, simply run extensions.get(in).

If you didn't know already, a HashMap allows you to assign a key to a value. In this case, the key is the file extension and value is the count.

Good day

Share Improve this answer Follow answered Mar 23, 2022 at 0:00 Chspsa's user avatar ChspsaChspsa 19711 bronze badges 8
  • I don't think this even close to the answer. – hfontanez Commented Mar 23, 2022 at 0:14
  • 1 op wanted to count file extensions. This is a way to do that. – Chspsa Commented Mar 23, 2022 at 0:21
  • 2 @hfontanez I don't think you understand the question. – Jawad El Fou Commented Mar 23, 2022 at 0:23
  • @JawadElFou quoting the OP "The issues is that now I want to count all the files in the folder by their extension". Count ALL the files by THEIR extension. Which means that you need to group all files by extension and provide a count of each grouping. Tell me what I didn't understand and how this code does exactly that? – hfontanez Commented Mar 23, 2022 at 0:29
  • 1 Well, I barely understand anything of that code, but it works for what I'm trying to do. Ty ^^ – DaniC Commented Mar 23, 2022 at 1:28
| Show 3 more comments 1

Using Java 8 or higher is actually not too difficult. First, you need to collect the items. Then, you need to group them by extension and create a map of extensions with the count.

public static void main(String[] args) throws IOException { Path start = Paths.get("C:/Users/Hector/Documents"); List<String> fileNames = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(start)){ for (Path entry : stream) { if (!Files.isDirectory(entry)) { fileNames.add(entry.getFileName().toString());// add file name in to name list } } } fileNames.stream().map(String::valueOf) .collect(Collectors.groupingBy(fileName -> fileName.substring(fileName.lastIndexOf(".")+1))) .entrySet().forEach(entry -> { System.out.println("File extension: " + entry.getKey() + ", Count: " + entry.getValue().size()); }); }

For my "Documents" directory enter image description here

Produced the following output

File extension: zargo~, Count: 3 File extension: txt, Count: 1 File extension: exe, Count: 1 File extension: pdf, Count: 3 File extension: ini, Count: 1 File extension: log, Count: 1 File extension: svg, Count: 1 File extension: zargo, Count: 3 File extension: lnk, Count: 1

The reason why I chose this solution over using Files.walk() is because this method can throw an AccessDeniedException which is problematic when you need to traverse different folders. However, if you can control access to a folder by calling canRead() method on the file object, then you could use it. I personally don't like it and many Java developers have issue with that function.

You could modify by adding it to a function that could be called recursively if the current path is a directory. Since the OP requirement is unclear if the count has to be for a given folder or the folder and all subfolders, I decided to just show the count for the current folder.

One last observation, when collecting the extensions, notice that I pass to the substring function to start from the last index of the period character. This is important to capture the real extension for files with multiple periods in the name. For example: Setup.x64.en-US_ProPlusRetail_RDD8N-JF2VC-W7CC6-TVXJC-3YF3D_TX_PR_act_1_OFFICE_13.exe. In a file, the extension always starts after the last period.

Share Improve this answer Follow edited Mar 23, 2022 at 4:47 answered Mar 23, 2022 at 0:48 hfontanez's user avatar hfontanezhfontanez 6,1482 gold badges28 silver badges42 bronze badges 2
  • 1 Files.walk was my first thought, when I sow this question. Well done. – Alexander Ivanchenko Commented Mar 23, 2022 at 8:57
  • @AlexanderIvanchenko also mine and pretty much every example there is out there for this type of problem. However, if you look under the surface, there is a lot of criticism as well. Because of this exception, you can't traverse full directory trees if the exception is thrown. – hfontanez Commented Mar 23, 2022 at 15:20
Add a comment |

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid …

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

Draft saved Draft discarded

Sign up or log in

Sign up using Google Sign up using Email and Password Submit

Post as a guest

Name Email

Required, but never shown

Post Your Answer Discard

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.

  • The Overflow Blog
  • The open-source ecosystem built to reduce tech debt
  • Featured on Meta
  • More network sites to see advertising test
  • We’re (finally!) going to the cloud!
  • Call for testers for an early access release of a Stack Overflow extension...
82 Counting the number of files in a directory using Java 4 How do I count the number of files with a specific extension on Android? 4 Count images in a directory 4 How can I count the number of files in a folder within a JAR? 1 How to count files in a directory 0 How to get number of files in a directory and subdirectory from a path in java? 1 By java how to count file numbers in a directory without list() 0 How to count the number of files in a directory, with the same file extension, in Java? 2 Java - Count all file extensions in a folder using DirectoryStream 2 Java.nio Files.walk() Java 8 List and count All Files And Directories

Hot Network Questions

  • Is it ever possible that the object is moving with a velocity such that its rate of change of speed is not constant but acceleration is constant?
  • Readability and error handling improvements for Python web scraping class
  • Employer changing resignation date to avoid holiday day pay
  • Counts repetitions within a list
  • What mnemonic helps differentiate 瑞士 (Switzerland) from 瑞典 (Sweden)?
  • routing LAN connections among clients on same ISP router device
  • A kind of "weak reference" which keeps the object alive, as long as there is otherwise-unused memory
  • Is there any way to grep a binary plist?
  • Should I Continue Studying Buffer Overflow Vulnerabilities?
  • What is the correct way to refer to Ferdinand de Saussure: “Saussure” or “de Saussure”?
  • Can I in Coq define a recursive function with a notation such that the recursive calls can use it?
  • What's the translation of "stand-up meeting" in French?
  • Can I pay everywhere in Singapore with an electronic wallet?
  • Did Jesus know people thoughts because he was God or because he was a man who acquired that "power" through prayer?
  • Is there a well-known digital logic circuit that outputs the last valid input on a high impedence input?
  • Does the ZX Spectrum's system variable PROG always hold 23755 (5CCBh)?
  • Could not find add method: AddExcludedTemplate (type: Sitecore.ContentSearch.SolrProvider.SolrIndexConfiguration)
  • What are the "rules" for counting transistors on a chip?
  • Draw stroke only outside of the path in TikZ
  • How to understand whether an electron in an atom is in superposition, ground or excited state?
  • What is the purpose for the blackbody radiation graph to be graphed using the below parameters?
  • Why do researchers wear white hats when handling lunar samples?
  • Phase cancellation in beams of light- edited
  • What is the largest distance at which a Cube-world is distinguishable from a spherical world?
more hot questions Question feed Subscribe to RSS Question feed

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-java

Từ khóa » đếm File