簡體   English   中英

如何使用 Java 查找文件是否存在於 hdfs 中?

[英]How to find if the file exists in hdfs using Java?

我正在嘗試查找 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<> files的鍵作為file_name參數傳遞給 function availableFiles 我構建了一個 jar 並在節點上運行它,它給了我以下 output:

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

不知道為什么會發生這種情況, _TRIG1_TRIG2_TRIG3存在,而_TRIG4_TRIG5不存在。 對於所有觸發器文件,它給了我相同的結果。 幫助。

從官方文檔中,您可以通過直接內部調用檢查您需要的文件是否存在:@see https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-common/FileSystemShell.html#測試

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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM