0

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".

Prince John Wesley
  • 62,492
  • 12
  • 87
  • 94
HShbib
  • 1,811
  • 3
  • 25
  • 47
  • Are you sure that you can't find a solution **[here](http://stackoverflow.com/questions/3154488/best-way-to-iterate-through-a-directory-in-java)**? – Till Helge Nov 01 '11 at 12:19
  • 1
    Not sure if I understand the question correctly... can't you simply use [java.io.listFiles](http://download.oracle.com/javase/6/docs/api/java/io/File.html#listFiles%28%29)? – S.L. Barth is on codidact.com Nov 01 '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 01 '11 at 12:30

5 Answers5

1

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.

Anders
  • 660
  • 3
  • 12
1
jmj
  • 237,923
  • 42
  • 401
  • 438
1

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.
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
0
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();

    for (int i= 0; i < filenames.length; i++) {
      System.out.println(filenames[i]);
    }
  }
}
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
  • it is showing null when I try to print the string. Rather than dirname I have entered the path for the files ?? – HShbib Nov 01 '11 at 12:35
-1
for (int i = 0; i < 40; i++) {
    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

dwalldorf
  • 1,379
  • 3
  • 12
  • 21