【问题标题】:Get filepath as string in java在java中获取文件路径作为字符串
【发布时间】:2018-01-27 11:52:19
【问题描述】:

我尝试了超过一千次,但我无法找到将所有文件路径作为字符串返回的方法,只能作为列表返回。例如,我希望名为 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());
        }
    }
}

这是我尝试过的示例代码,但没有返回任何内容。我需要将 filePaths 作为字符串返回,因为我正在尝试使用 this 方法获取 md5。

提前致谢。

【问题讨论】:

标签: java string filepath


【解决方案1】:

删除第一行后,您的代码可以正常工作。然后它会打印一个包含完整路径的文件列表。

如果您还想打印 MD5 和,您可以从您引用的代码中选择相关部分。这不是太多,因为你已经在循环中有 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());
        }
    }
}

因为我不太喜欢对外部库的依赖,尤其是它会将整个文件加载到内存中(toByteArray 调用表明这一点),所以这里是第一个 if 的替代品,没有 Apache Commons 并且没有将整个文件加载到数组中,但需要一个 throws NoSuchAlgorithmException 作为方法头或一个额外的 try-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()){
...

或者一个不抛出异常并且不依赖于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()){
...

这是我用于测试的实际代码 (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());
                }
            }
    }
}

我只是直接从 NetBeans/Eclipse 项目文件夹中运行它(这是硬编码 "." 的结果),然后它列出了子目录中的各种项目文件、.java 文件本身等。

【讨论】:

  • 代码运行没有问题,但我在控制台中看不到任何输出。
  • @SouvannasouckMark 您正在测试哪个变体?由于我的 PC 上缺少 Apache Commons,我不得不假设所引用的文章正确使用了它。但是,两个带有 DigestInputStream 的 sn-ps 肯定可以工作,它们是直接从工作测试代码复制到这里的。旁注:当代码从空文件夹启动时,甚至在不包含文件的文件夹层次结构中启动时,代码合法地不会输出任何内容。也可能不会列出隐藏文件。
  • @SouvannasouckMark:为最后一个变体添加了完整的代码,只是为了确定,请参阅水平分隔符下方。
  • 现在谢谢它为每个文件做 MD5,但只在项目文件夹中。我如何让它为 C:\\ 中的每个文件做 MD5?
  • @SouvannasouckMark 查看当前版本。请记住,典型的 c: 驱动器上有很多文件。
【解决方案2】:

您可以使用Files 轻松实现它:

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

【讨论】:

  • 我需要它作为一个字符串而不是一个列表。但是谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-15
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多