简体   繁体   English

在java中获取文件路径作为字符串

[英]Get filepath as string in java

I tried over a thousand times and I can't figure out a way to return all file paths as a string, only as a list. 我尝试了1000多次,但我想不出一种将所有文件路径作为字符串(仅作为列表)返回的方法。 For example, I want the string called filePath to return c:/users/exampleuser/file.txt but for all the files in a directory and it's subdirectory. 例如,我希望名为filePath的字符串返回c:/users/exampleuser/file.txt但要返回目录及其子目录中的所有文件。

public void listFilesAndFilesSubDirectories(String directoryName){
     directoryName = "C:\\";
    File directory = new File(directoryName);
    //get all the files from a directory
    File[] fList = directory.listFiles();
    for (File files : fList){
        if (files.isFile()){
            System.out.println(files.getAbsolutePath());
        } else if (files.isDirectory()){
            listFilesAndFilesSubDirectories(files.getAbsolutePath());
        }
    }
}

This is an example code I tried but returns nothing. 这是我尝试的示例代码,但未返回任何内容。 I need to return the filePaths as a string because I am trying to get the md5 using this method. 我需要以字符串形式返回filePaths,因为我正在尝试使用方法获取md5。

Thanks in advance. 提前致谢。

You can use Files to implement it in the easy way : 您可以使用Files以简单的方式实现它:

public List<String> listFilesAndFilesSubDirectories(String directoryName) throws IOException {
      return Files.walk(Paths.get(directoryName))
        .map(Path::toFile)
        .map(File::getAbsolutePath)
        .collect(Collectors.toList());
}

Your code works fine after removing the first line. 删除第一行后,您的代码可以正常工作。 Then it prints a list of files, with full path. 然后,它将打印出具有完整路径的文件列表。

If you also want to print MD5 sums, you can just pick the relevant parts from the code you refer. 如果您还想打印MD5总和,则只需从引用的代码中选择相关部分。 Which are not too many, as you have File objects in the loop already, so you need that single line with the md5 thing: 并不是很多,因为您已经在循环中添加了File对象,因此您需要使用md5这样的一行:

public static void listFilesAndFilesSubDirectories(String directoryName){
    File directory = new File(directoryName);
    //get all the files from a directory
    File[] fList = directory.listFiles();
    for (File file : fList){
        if (file.isFile()){
            System.out.print(file.getAbsolutePath());
            try(FileInputStream fis=new FileInputStream(file)){
                System.out.println(" - MD5: "+DigestUtils.md5Hex(IOUtils.toByteArray(fileInputStream)));
            }catch(Exception ex){
                System.out.println(" - Error: "+ex);
            }
        } else if (file.isDirectory()){
            listFilesAndFilesSubDirectories(file.getAbsolutePath());
        }
    }
}

As I do not really like the dependence on an external library, and especially the fact that it loads the entire file in the memory (the toByteArray call indicates it), here is a replacement for the first if , without Apache Commons and without loading the entire file into an array, but requiring a throws NoSuchAlgorithmException for the method header or an extra try - catch somewhere: 由于我不太喜欢依赖外部库,尤其是它将整个文件加载到内存中的事实( toByteArray调用表明了这一点),因此,这里是第一个if的替代品,没有Apache Commons,也没有加载将整个文件放入一个数组,但需要为方法标题throws NoSuchAlgorithmException或进行额外的try - catch某处catch

...
if (file.isFile()){
    System.out.print(file.getAbsolutePath());
    try(DigestInputStream dis=new DigestInputStream(new BufferedInputStream(new FileInputStream(file)), MessageDigest.getInstance("MD5"))){
        while(dis.read()>=0);
        System.out.println(" - MD5: "+javax.xml.bind.DatatypeConverter.printHexBinary(dis.getMessageDigest().digest()));
    }catch(Exception ex){
        System.out.println(" - Error: "+ex);
    }
} else if (file.isDirectory()){
...

Or a long one which throws no exception and does not depend on javax stuff either (which is not necessarily present after all): 或者一个长的不抛出异常并且也不依赖于javax东西(毕竟不一定存在):

...
if (file.isFile()){
    System.out.print(file.getAbsolutePath());
    MessageDigest md5=null;
    try{md5=MessageDigest.getInstance("MD5");}catch(NoSuchAlgorithmException nsae){};
    try(DigestInputStream dis=new DigestInputStream(new BufferedInputStream(new FileInputStream(file)), md5)){
        while(dis.read()>=0);
        System.out.print(" - MD5: ");
        for(Byte b: md5.digest())
            System.out.printf("%02X",b);
        System.out.println();
    }catch(IOException ioe){
        System.out.println(" - Error: "+ioe);
    }
} else if (file.isDirectory()){
...

Here is the actual code ( RecDir.java ) I used for testing, now modified for c:\\ (which includes an additional check for dealing with directories you have no right to access): 这是我用于测试的实际代码( RecDir.java ),现在针对c:\\进行了修改(其中包括对处理您无权访问的目录的其他检查):

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class RecDir {
    public static void main(String[] args) {
        listFilesAndFilesSubDirectories("c:\\");
    }
    public static void listFilesAndFilesSubDirectories(String directoryName){
        File directory = new File(directoryName);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        if(fList!=null)
            for (File file : fList){
                if (file.isFile()){
                    System.out.print(file.getAbsolutePath());
                    MessageDigest md5=null;
                    try{md5=MessageDigest.getInstance("MD5");}catch(NoSuchAlgorithmException nsae){};
                    try(DigestInputStream dis=new DigestInputStream(new BufferedInputStream(new FileInputStream(file)), md5)){
                        while(dis.read()>=0);
                        System.out.print(" - MD5: ");
                        for(Byte b: md5.digest())
                            System.out.printf("%02x",b);
                        System.out.println();
                    }catch(IOException ioe){
                        System.out.println(" - Error: "+ioe);
                    }
                } else if (file.isDirectory()){
                    listFilesAndFilesSubDirectories(file.getAbsolutePath());
                }
            }
    }
}

I just ran it directly from NetBeans/Eclipse project folder (that is what the hardcoded "." results in), and then it lists various project files in the subdirectories, the .java file itself, etc. 我只是直接从NetBeans / Eclipse项目文件夹中运行它(这是硬编码的 "."结果),然后它在子目录中列出了各种项目文件,.java文件本身,等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM