【问题标题】:How to find if the file exists in hdfs using Java?如何使用Java查找文件是否存在于hdfs中?
【发布时间】:2020-07-24 17:20:17
【问题描述】:

我正在尝试查找触发器文件是否存在于 hdfs 目录中。

代码:

    private static final int index = 23;
    @SuppressWarnings("serial")
    private static HashMap<String, Boolean> files = new HashMap<String, Boolean>() {{
        put("/user/ct_troy/allfiles/_TRIG1", false);
        put("/user/ct_troy/allfiles/_TRIG2", false);
        put("/user/ct_troy/allfiles/_TRIG3", false);
        put("/user/ct_troy/allfiles/_TRIG4", false);
        put("/user/ct_troy/allfiles/_TRIG5", false);
    }};

    private static boolean availableFiles(String file_name){
        Configuration config = new Configuration();
        config.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
        config.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName());
        try {
            FileSystem hdfs = FileSystem.get(config);
            // Hadoop DFS Path - Input file
            Path path = new Path(file_name); // file_name - complete path and file name.
            // Check if input is valid
            if (hdfs.exists(path) == false) {
                System.out.println(file_name + " not found.");
                throw new FileNotFoundException(file_name.substring(index));
            }
            else{
                    System.out.println(file_name + " File Present.");
                    return true;
                }
            }catch (IOException e) {
            }
        return false;
    }

我将HashMap&lt;&gt; files 的键作为file_name 参数传递给函数availableFiles。 我构建了一个 jar 并在节点上运行它,它给了我以下输出:

_TRIG2 not found.
_TRIG3 not found.
_TRIG1 not found.
_TRIG4 not found.
_TRIG5 not found.

不确定为什么会发生这种情况,_TRIG1_TRIG2_TRIG3 存在,而 _TRIG4_TRIG5 不存在。对于所有触发器文件,它给了我相同的结果。帮助。

【问题讨论】:

标签: java maven hdfs hadoop2


【解决方案1】:

从官方文档中,您可以通过直接内部调用来检查您需要的文件是否存在:@see https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-common/FileSystemShell.html#test

test

Usage: hadoop fs -test -[defswrz] URI

Options:

    -d: f the path is a directory, return 0.
    -e: if the path exists, return 0.
    -f: if the path is a file, return 0.
    -s: if the path is not empty, return 0.
    -w: if the path exists and write permission is granted, return 0.
    -r: if the path exists and read permission is granted, return 0.
    -z: if the file is zero length, return 0.

Example:

    hadoop fs -test -e filename

您的 java 代码看起来不错。也许你的 if 测试写得不好:

if (!hdfs.exists(path)) { // <=================== @see the change and test it.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 2017-01-28
    相关资源
    最近更新 更多