如何在只知道目录的相对路径时读取目录内的文件。

huangapple go评论79阅读模式
英文:

How to read the files inside a directory when Only Relative path of directory is known

问题

在我的Java应用程序中,

  1. 我有相对路径的目录(目录及其中的文件是构建的一部分)。
  2. 该目录包含多个文件。
  3. 我想读取父目录中的文件名。
  4. 文件以后可能会更改,并且数量很多,因此我不知道文件的名称,也不希望我的代码在添加、删除或重命名文件时发生变化

由于我事先不知道文件的名称,因为它们可能会后来更改(有多个文件可以根据环境变化而变化)。我只知道文件的父目录的相对路径。

我应该如何读取这些文件?

英文:

In my java application, <br>

  1. I have relative path of the directory (Directory and files in it are part of the build). <br>
    2.The directory contains multiple files. <br>
  2. I want to read the file names in the parent directory.<br>
  3. Files can change later and are many in number, So I do not know the names of the files and Do not want my code to change if more files are added or removed or renamed<br>

Now as I do not know the names of the files before hand as they may change later (there are multiple files which can vary according to environment). I only know about the relative path of the parent directory of the files.

How do I read the files ?

答案1

得分: 1

你可以通过文件类的file.getlistFiles()方法获取该目录的所有文件列表。它返回一个文件数组。甚至可以为您的文件定义过滤器,以便返回您想要的文件。

try {
    File f = new File("D:/Programming");

    FilenameFilter filter = new FilenameFilter() {
        @Override
        public boolean accept(File f, String name) {
            // 我们只想找以 .c 结尾的文件
            return name.endsWith(".c");
        }
    };

    // 注意,这次我们使用 File 类作为数组,而不是 String
    File[] files = f.listFiles(filter);
    // 查看示例链接:https://stackabuse.com/java-list-files-in-a-directory/
} catch (Exception e) {
    e.printStackTrace();
}

// 如果要使用相对路径,可以使用以下方法
String relativePath = System.getProperty("user.dir");
// 它将返回您放置应用程序的文件夹。
// 如果您的文件夹有一些子文件夹,您可以简单地使用 file.list() 方法;
// 它会返回您的目录中所有文件和文件夹的名称数组。
String[] listOfMyFilesAndFolders = file.list();
// 您可以将这些名称添加到您的路径中,以访问其他文件夹。

// 您可以通过以下方式检查路径是文件还是文件夹
if (file.isDirectory()) {
    for (String path : listOfFilesAndFolders) {
        File file = new File(basePath + path);
        if (file.isDirectory()) {
            // 它是一个文件夹,您可以使用另一个循环或递归来导航子文件夹
        } else {
            // 它是一个文件,您可以执行您想要的任何操作
        }
    }
}

// 我认为您可以使用递归来遍历子文件夹,使用递归可以在子目录中遍历,详细了解请参阅链接:https://www.javatpoint.com/recursion-in-java
我希望这能有所帮助

<details>
<summary>英文:</summary>

You can get list of all files of that directory by file.getlistFiles() method of file class.
It returns an array of files.
Even you can define filter for your files, so it returns exactly files that you want.

    try {
        File f = new File(&quot;D:/Programming&quot;);

        FilenameFilter filter = new FilenameFilter() {
            @Override
            public boolean accept(File f, String name) {
                // We want to find only .c files
                return name.endsWith(&quot;.c&quot;);
            }
        };

        // Note that this time we are using a File class as an array,
        // instead of String
        File[] files = f.listFiles(filter);
look at [this](https://stackabuse.com/java-list-files-in-a-directory/) example.&lt;/br&gt; 
If you want to use relative  path, You can use 

    System.getProperty(&quot;user.dir&quot;);
    String relative  Path =System.getProperty(&quot;user.dir&quot;);
it returns the folder that you put your app in it.
If your folder has some subfolders, you can simply use file.list();
it returns names of all files and folders of your directory .
String [] listOfMyFilesAndFolders =file.list();
you can add these names to your path to access another folders.
You can check your path is a file or is a folder by using 

    file.isDirectory();
    for ( String path: listOfFilesAndFolders ) {
    File file = new File(basePath+path);
    if ( file.isDirectory() {
    // it is a folder and you can use another for loop or recursion to navigate sub directories
    } else {
    // it is  a file and you can do everyThing you want}}
I think that you can use recursion to walk in your sub directories use [recursion](https://www.javatpoint.com/recursion-in-java) to read more
    I hope helps.

</details>



# 答案2
**得分**: 0

代码部分不要翻译只返回翻译好的部分如下所示

问题提问得很糟糕文字含糊不清
我有目录的相对路径目录和其中的文件是构建的一部分)”意义不明你必须阐明你的意思

假设你通过命令行参数获得一个相对目录例如/folder1/folder2”),基本上有3种选择

1将程序以jar所在的目录作为当前目录启动以便它可以用作工作目录这种方法要求当你通过`java -jar myapp.jar`命令启动应用程序时首先要在前面加上一个cd命令将自己直接置于目录中代码将类似于@hamidreza75的解决方案但显然你不会有变量D:/Programming”,而直接是要读取文件的目录的相对路径

启动脚本

```batch
@echo off
cd {jar-folder}
java -jar myapp.jar

Java代码:

package com.sample.stack;

import java.io.File;
import java.io.FilenameFilter;

public class FileRenamenter {
    public static void main(String[] args) {
        final String relativePath = "folder1/folder2";
        File directory = new File(relativePath);
        String[] list = directory.list(new FilenameFilter(){
            public boolean accept(File dir, String name) {
                // filter condition
                return true;
            }
        });
        // echo file list
        for (String filePath : list) {
            System.out.println(filePath);
        }
    }
}

2)通过命令行参数传递要控制的文件夹,像这样:

启动脚本:

@echo off
java -jar {jar-folder}/myapp.jar {jar-folder}

Java代码(只有“directory”变量变化):

File directory = new File(args[0], relativePath); // 注意 args[0]

3)以编程方式找到jar所在的文件夹[非常不鼓励的做法],然后连接相对路径:

Java代码(只有“directory”变量变化):

String jarFolder = ClassLoader.getSystemClassLoader().getResource(".").getPath();
File directory = new File(jarFolder, relativePath); // 注意 jarFolder
英文:

the question is badly asked and the text is misleading.
"I have relative path of the directory (Directory and files in it are part of the build)" means little and nothing, you have to clarify what you mean.

Assuming you get a relative directory (for example "/folder1/folder2") via command line parameter, you basically have 3 choices:

  1. start the program with the directory in which the jar is located as the "current directory", so that it can be used as a working directory. This approach requires that when you launch your application via the java -jar myapp.jar command first you prepend a "cd" command to place yourself directly in the directory. The code will look like the @hamidreza75 solution but obviously you will not have the variable "D: / Programming" but directly the relative path of the directory in which to read the files.

launch script

@echo off
cd {jar-folder}
java -jar myapp.jar

java code:

package com.sample.stack;
import java.io.File;
import java.io.FilenameFilter;
public class FileRenamenter {
public static void main(String[] args) {
final String relativePath = &quot;folder1/folder2&quot;;
File directory = new File(relativePath);
String[] list = directory.list(new FilenameFilter(){
public boolean accept(File dir, String name) {
// filter condition
return true;
}
});
// echo file list
for (String filePath : list) {
System.out.println(filePath);
}
}
}
  1. pass the folder to be controlled via command line parameter, like this:

launch script

@echo off
java -jar {jar-folder}/myapp.jar {jar-folder}

java code (only the "directory" variable changes)

File directory = new File(args[0], relativePath); // note args[0]
  1. programmatically find the folder in which the jar is running [very discouraged practice] and then concatenate the relative path:

java code (only the "directory" variable changes):

String jarFolder = ClassLoader.getSystemClassLoader().getResource(&quot;.&quot;).getPath();
File directory = new File(jarFolder, relativePath); // note jarFolder

huangapple
  • 本文由 发表于 2020年4月7日 12:47:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/61073008.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定