2

I need to make a menu that list the .txt files in a directory. For example, if i have jonsmith12.txt , lenovo123.txt , dell123.txt in the directory how would I make an arraylist menu of:

Please choose one of the following:

  1. jonsmith12
  2. lenovo123
  3. dell123

Please enter your choice:

I need an arraylist menu is because I don't know how many .txt files are in the directory at any given time.

import java.io.File;

public class ListFiles 
{

    public static void listRecord() {

  // Directory path here
  String path = "."; 

  String files;
  File folder = new File(path);
  File[] listOfFiles = folder.listFiles(); 

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

   if (listOfFiles[i].isFile()) 
   {
   files = listOfFiles[i].getName();
       if (files.endsWith(".txt") || files.endsWith(".TXT"))
       {
          System.out.println(files);
        }
     }
  }
}
}

Here is the class that will display the information in the .txt file onto the console. It stills need some modifying too but I could probably figure that out.

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * This program reads a text file line by line and print to the console. It uses
 * FileOutputStream to read the file.
 * 
 */
public class DisplayRec {

    public static void displayRecord() throws IOException {

    File file = new File("williamguo5.txt");
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    DataInputStream dis = null;

    try {
      fis = new FileInputStream(file);

      // Here BufferedInputStream is added for fast reading.
      bis = new BufferedInputStream(fis);
      dis = new DataInputStream(bis);

      // dis.available() returns 0 if the file does not have more lines.
      while (dis.available() != 0) {

      // this statement reads the line from the file and print it to
        // the console.
        System.out.println(dis.readLine());
      }

      // dispose all the resources after using them.
      fis.close();
      bis.close();
      dis.close();

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

So the question is: How do I implement a ArrayList menu into my ListFiles class so it will display the .txt files.

3
  • How do I implement a ArrayList menu into my ListFiles class so it will display the .txt files. Commented May 14, 2012 at 19:44
  • 4
    If this is homework, please tag it as such. Now, what have you tried? What didn't work? Do you even have a menu class/method yet? Commented May 14, 2012 at 19:47
  • Did you try making an ArrayList and adding matching files to it? Commented May 14, 2012 at 19:49

2 Answers 2

1

You can use the alternate method signature for File.listFiles(FilenameFilter filter) to simplify your code:

File[] files = dir.listFiles(new FilenameFilter() {

    @Override
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt");
    }
});

And unless you really enjoy writing loops, you don't even need to manually loop over the array to convert it to a List:

List<File> lstRecords = Arrays.asList(files);

Your displayRecord method was pretty close; you just needed to pass the file as an argument and use that instead of a hard-coded filename, and you needed to initialize dis.

Putting it all together:

package com.example.file;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class FileExample {

    public static List<File> listRecords(File dir) {
        File[] files = dir.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".txt");
            }
        });

        return Arrays.asList(files);
    }

    public static void displayRecord(File file) {
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        DataInputStream dis = null;

        try {
            fis = new FileInputStream(file);

            // Here BufferedInputStream is added for fast reading.
            bis = new BufferedInputStream(fis);
            dis = new DataInputStream(bis);

            String line = dis.readLine();
            while (line != null) {

                // this statement reads the line from the file and print it to
                // the console.
                System.out.println(line);
                line = dis.readLine();
            }

            // dispose all the resources after using them.
            fis.close();
            bis.close();
            dis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {

        List<File> lstRecords = listRecords(new File("."));
        for (File record : lstRecords) {
            displayRecord(record);
        }
    }

}

It's also better to use Reader/Writer instead of InputStream/OutputStream if you're working with text files, and you should close your files in the finally block to avoid a potential resource leak.

You'll also notice I didn't explicitly use an ArrayList. In most cases, it's better to program against the interface (in this case, List) as much as possible, and only declare variables using the implementing class when you need to use a method that's only available to that class.

Sign up to request clarification or add additional context in comments.

Comments

0

It looks like your sticking point above is the array. If you just need to iterate over the files in a directory, something as simple as the following will do the trick.

import java.io.File;


public class TxtEnumerator {
    public static void main(String[] args) {
        TxtEnumerator te = new TxtEnumerator();
        te.listFiles();
    }

    public void listFiles() {
        String filepath = "." + File.separator + "textDirectory";
        File file = new File(filepath);
        if (file.isDirectory()) {
            for (File f : file.listFiles()) {
                if (f.getName().endsWith(".txt")) {
                    System.out.println(f.getName());
                }
            }
        }
    }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.