开发者

Indexing File Names To a Database

开发者 https://www.devze.com 2022-12-31 14:15 出处:网络
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?

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 a开发者_运维技巧lready know.


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();
    }
}


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消