tags:

views:

66

answers:

3

I have a folder with more than 2000 files and I need to index their file names on a database(MySQL) using Java, but how could I do this?

PS: The MySQL connection part I already know.

+1  A: 

I'm not sure what precisely the problem is. If it's reading the filenames from the directory, take a look at File.listFiles().

Brian Agnew
+1  A: 

Check File.listFiles

public File[] listFiles()

Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

If this abstract pathname does not denote a directory, then this method returns null. Otherwise an array of File objects is returned, one for each file or directory in the directory. Pathnames denoting the directory itself and the directory's parent directory are not included in the result. Each resulting abstract pathname is constructed from this abstract pathname using the File(File, String) constructor. Therefore if this pathname is absolute then each resulting pathname is absolute; if this pathname is relative then each resulting pathname will be relative to the same directory.

Zak
+2  A: 

You can recursively list all the files in a directory like this:

import java.io.*;

public class ListDir {

    public static void main(String args[]) {
        File root;
        if (args.length > 0) root = new File(args[0]);
        else root = new File(System.getProperty("user.dir"));
        ls(root); 
    }

    private static void ls(File f) { 
        File[] list = f.listFiles();
        for (File file : list) {
            if (file.isDirectory()) ls(file);
            else System.out.println(file);
        }
    }
}

See also Using Prepared Statements. Maybe something like this:

PreparedStatement ps = conn.prepareStatement("INSERT INTO Files VALUES(?)");
File userDir = new File(System.getProperty("user.dir"));
File[] files = userDir.listFiles();
for (File f : files) {
    if (f.isFile()) {
        ps.setString(1, f.getAbsolutePath());
        ps.executeUpdate();
    }
}
trashgod
And I could do this: `"INSERT " + filenames "rest of the SQL statement"`, with `filenames` as the returned variable from `ls(root)`?
Nathan Campos
I'd use a `PreparedStatement` and call `setString()` instead of `println()` to insert a row for each file.
trashgod
Thanks, I'm reading that docs and I'm sure that I can continue from here.
Nathan Campos
Excellent! Also, thank you for fixing my typo. :-)
trashgod
@trashgod: How could I put `file` inside a `String` that will have the commas to be used on the `setString()`?
Nathan Campos
I outlined some code above; update your question with your `CREATE TABLE...` statement.
trashgod
Thanks very much!
Nathan Campos
If it's getting slow, consider using `addBatch()` instead of `executeUpdate()` and do `executeBatch()` on every 1000th item or so.
BalusC