Take the 2-minute tour ×

I am trying to index multiple file names (.txt) in an array.

for example

static String[] filename = new String[40];

and I have 40 files in the project directory. I want to insert their names into an array using a for loop rather than typing it manually. filename[0] = ".txt".

share|improve this question
Are you sure that you can't find a solution here? –  Till Helge Nov 1 '11 at 12:19
Not sure if I understand the question correctly... can't you simply use java.io.listFiles? –  S.L. Barth Nov 1 '11 at 12:19
@Till Helge Helwiq: I tried it an it is giving me an error on showFiles(files). I have entered the project directory path where the files are located. Still not working –  HShbib Nov 1 '11 at 12:30

5 Answers 5

I would look at creating a File object (to the directory containing the files you want to list), then invoking listFiles()-method iterating over the files and populating your String array from that.

share|improve this answer
share|improve this answer

Implement a FilenameFilter that accepts files with names ending .txt.

Pass that filter to theFile.listFiles(FilenameFilter) to get a nice File[] that will contain the text files located in the directory represented by theFile.

And forget:

  1. Keeping a String[] of names that represent File[]. If a File is needed, keep an array of File.
  2. Using an expandable list (ArrayList, Vector) - it is not necessary.
share|improve this answer
File dir = new File(dirname);

String[] filenames = dir.list();

Edit: Sample program that lists the files in the current directory:

import java.io.*;

class dir {

  public static void main(String[] argv) {
    File dir = new File(".");
    String[] filenames = dir.list();

share|improve this answer
it is showing null when I try to print the string. Rather than dirname I have entered the path for the files ?? –  HShbib Nov 1 '11 at 12:35
Works for me. See edit above. –  Klas Lindbäck Nov 1 '11 at 13:05
    filename[i] = ".txt";

Beside the fact that String[] is not really the best solution for that.. What about using an ArrayList? http://download.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html

share|improve this answer

Your Answer


