如何使用hdfsapi返回文件格式hdfs的列表

bzzcjhmw  于 2021-07-13  发布在  Hadoop
关注(0)|答案(1)|浏览(352)

我创建了一个java函数来在hdfs中打开一个文件。该函数仅用于api hdfs。我的代码中不使用任何hadoop依赖项。我的职能运作良好:

public static openFile()
    {
        System.out.print("main for testing the Hdfs WEB API");
        URL url = new URL("http://URI/webhdfs/v1/PATH_TO_File?op=OPEN");

        try {
                HttpURLConnection con = (HttpURLConnection) url.openConnection() ;
                con.setRequestMethod("GET");
                con.setDoInput(true);
                InputStream in = con.getInputStream();
                int ch;
                while((ch=in.read())!=-1)
                {
                    System.out.print((char) ch);
                }

            } catch (IOException e) {

                e.printStackTrace();
            }
    }

我正在做一个新函数来返回hdfs中的文件列表。第二个功能是:

public static ListFile()
        {
            System.out.print("main for testing the Hdfs WEB API");
            URL url = new URL("http://URI/webhdfs/v1/PATH_TO_File?op=LISTSTATUS");

            try {
                    HttpURLConnection con = (HttpURLConnection) url.openConnection() ;
                    con.setRequestMethod("GET");
                    con.setDoInput(true);
                    InputStream in = con.getInputStream();

                    logger.info("list is '{}' ", url.openStream());

                } catch (IOException e) {

                    e.printStackTrace();
                }
        }

你能帮我一下吗,我怎样用流返回hdfs中的文件列表,用扫描仪得到响应?当我在浏览器中运行url时,我知道它们运行得很好。提前谢谢

yzxexxkh

yzxexxkh1#

您可以使用与第一个解决方案完全相同的逻辑,但这一次,使用stringbuilder来获取完整的响应,然后需要使用json库对其进行解析。

InputStream in = con.getInputStream();
int ch;
StringBuilder sb = new StringBuilder();
while((ch=in.read())!=-1) {
    sb.append((char) ch);
}
String response = sb.toString();
// TODO: parse response string

注意:像reformation/gson这样的库会使这更简单

相关问题