Question

Using listAllFiles as a guide, write a method that has one File argument: if the argument...

Using listAllFiles as a guide, write a method that has one File argument: if the argument is a directory, the method returns the total number of files below it. If the argument represents a file, the method just returns 1. public static int countFiles(File f)  

import java.io.File;

public class FileLister
{
  public static void main(String[] args)
  {
    // Choose the directory you want to list.
    // If running in Eclipse, "." will just be the current project directory.
    // Use ".." to list the whole workspace directory, or enter a path to
    // some other directory.
    File rootDirectory = new File(".");

    listAllFiles(rootDirectory);
  }
  
  /**
   * Print the names of all items in the hierarchy located under 
   * a given directory. If the given File object is not a directory, 
   * just prints the file's name.
   */
  public static void listAllFiles(File f)
  {
    if (!f.isDirectory())
    {
      // Base case: f is a file, so just print its name
      System.out.println(f.getName());
    }
    else
    {
      // Recursive case: f is a directory, so go through the 
      // files and directories it contains, and recursively call
      // this method on each one
      System.out.println("+ " + f.getName());
      File[] files = f.listFiles();
      for (int i = 0; i < files.length; ++i)
      {
        listAllFiles(files[i]);
      }
    }
  }
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1


import java.io.File;

public class FileLister
{
   public static void main(String[] args)
   {
       // Choose the directory you want to list.
       // If running in Eclipse, "." will just be the current project directory.
       // Use ".." to list the whole workspace directory, or enter a path to
       // some other directory.
       File rootDirectory = new File(".");

       listAllFiles(rootDirectory);
   }

   public static int countFiles(File f) {

       if(f.isFile())
           return 1;
       else{
           return f.list().length;
       }
   }

   /**
   * Print the names of all items in the hierarchy located under
   * a given directory. If the given File object is not a directory,
   * just prints the file's name.
   */
   public static void listAllFiles(File f)
   {
       if (!f.isDirectory())
       {
           // Base case: f is a file, so just print its name
           System.out.println(f.getName());
       }
       else
       {
           // Recursive case: f is a directory, so go through the
           // files and directories it contains, and recursively call
           // this method on each one
           System.out.println("+ " + f.getName());
           File[] files = f.listFiles();
           for (int i = 0; i < files.length; ++i)
           {
               listAllFiles(files[i]);
           }
       }
   }
}

Add a comment
Know the answer?
Add Answer to:
Using listAllFiles as a guide, write a method that has one File argument: if the argument...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Trying to practice this assignment Argument list: the *yahoonews.txt Data file: yahoonews.txt Wr...

    Trying to practice this assignment Argument list: the *yahoonews.txt Data file: yahoonews.txt Write a program named WordCount.java, in this program, implement two static methods as specified below: public static int countWord(Sting word, String str) this method counts the number of occurrence of the word in the String (str) public static int countWord(String word, File file) This method counts the number of occurrence of the word in the file. Ignore case in the word. Possible punctuation and symbals in the file...

  • How do I correct this error in my code? When it got to the file type...

    How do I correct this error in my code? When it got to the file type I can only go "null" from a certain point and I'm wondering how to correct this error. Also can I get a word document on this coding strategy for this problem? How much of this am I doing correctly? The original problem description: Create a program that provides a listing of all the files in a directory. The program should be a Java application...

  • I have one method {search()} that search for a particular file in a directory that the filename s...

    I have one method {search()} that search for a particular file in a directory that the filename start by "B" and it will return the files. I have 2 file that start by B [Bcc.txt, Ba.txt]. But in main method I want to count a word "light" how many times it appeares in the each files [Bcc.txt, Ba.txt]. However, I really don't know how to do it. I need help on that. public class CountWord {    public static void main(String[]...

  • Hi, So I have a finished class for the most part aside of the toFile method...

    Hi, So I have a finished class for the most part aside of the toFile method that takes a file absolute path +file name and writes to that file. I'd like to write everything that is in my run method also the toFile method. (They are the last two methods in the class). When I write to the file this is what I get. Instead of the desired That I get to my counsel. I am having trouble writing my...

  • I need to write a program in java that reads a text file with a list...

    I need to write a program in java that reads a text file with a list of numbers and sorts them from least to greatest. This is the starter file. import java.util.*; import java.io.*; public class Lab3 { static final int INITIAL_CAPACITY = 5; public static void main( String args[] ) throws Exception { // ALWAYS TEST FOR REQUIRED INPUT FILE NAME ON THE COMMAND LINE if (args.length < 1 ) { System.out.println("\nusage: C:\\> java Lab3 L3input.txt\n"); System.exit(0); } //...

  • How to complete these methods: /**    * Returns a reference to the course with title equals to the argument. This    * m...

    How to complete these methods: /**    * Returns a reference to the course with title equals to the argument. This    * method searches in the courses stored in the HashMap {@code courses} to find    * the course whose title equals to the argument {@code title}. If the course is    * not found, {@code null} is returned.    *    * @param title the title of the course    * @return a reference to the course, or {@code null} if the course is not   ...

  • Ask the user for the name of a file and a word. Using the FileStats class,...

    Ask the user for the name of a file and a word. Using the FileStats class, show how many lines the file has and how many lines contain the text. Standard Input                 Files in the same directory romeo-and-juliet.txt the romeo-and-juliet.txt Required Output Enter a filename\n romeo-and-juliet.txt has 5268 lines\n Enter some text\n 1137 line(s) contain "the"\n Your Program's Output Enter a filename\n romeo-and-juliet.txt has 5268 lines\n Enter some text\n 553 line(s) contain "the"\n (Your output is too short.) My...

  • Create a method based program to find if a number is prime and then print all...

    Create a method based program to find if a number is prime and then print all the prime numbers from 1 through 500 Method Name: isPrime(int num) and returns a boolean Use for loop to capture all the prime numbers (1 through 500) Create a file to add the list of prime numbers Working Files: public class IsPrimeMethod {    public static void main(String[] args)    {       String input;        // To hold keyboard input       String message;      // Message...

  • JAVA Write a method that accepts a String as an argument. The method should use recursion...

    JAVA Write a method that accepts a String as an argument. The method should use recursion to display each individual character in the String. Then, modify the method you just wrote so it displays the String backwards. The following code does not correctly display the String backwards. It merely moves the first character of the String to the end: public static void displayCharacter(String s)    {        if(s.length() == 0)            return;        else       ...

  • . In the method main, prompt the user for a non-negative integer and store it in...

    . In the method main, prompt the user for a non-negative integer and store it in an int variable num (Data validation is not required for the lab). Create an int array whose size equals num+10. Initialize the array with random integers between 0 and 50 (including 0 and excluding 50). Hint: See Topic 4 Decision Structures and File IO slides page 42 for how to generate a random integer between 0 (inclusive) and bound (exclusive) by using bound in...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT