Hadoop學習--經過API獲得文件系統狀態--day04

import java.io.ByteArrayOutputStream;java

import java.io.InputStream;apache

import java.net.URL;分佈式


import org.apache.hadoop.conf.Configuration;ide

import org.apache.hadoop.fs.BlockLocation;工具

import org.apache.hadoop.fs.FSDataInputStream;oop

import org.apache.hadoop.fs.FileStatus;測試

import org.apache.hadoop.fs.FileSystem;spa

import org.apache.hadoop.fs.FsUrlStreamHandlerFactory;.net

import org.apache.hadoop.fs.Path;xml

import org.apache.hadoop.io.IOUtils;

import org.junit.Test;


/**

 * 測試hadoop文件系統的API

 * @author Administrator

 *

 */

public class readfilestatus {


/**

* 經過filesystem對象API讀取HDFS文件數據

* @author Administrator

* 1.建立configuration對象,注意這裏若是涉及到某些參數,須要本身書寫指定在src目錄下

* 2.利用filesystem的get方法來獲取filesystem對象,get方法一共有三種(關鍵)

* 3.利用filesystem的open方法打開一個數據輸入流,方法過程當中須要一個path對象的參數傳遞(關鍵)

* 4.利用ioutils工具類實現文件的輸出

*/

@Test

public void read() throws Exception {

//建立configuration對象,有個默認的加載順序,先從core-default.xml,再到src目錄中的文件,這裏

//咱們給定了

        Configuration conf = new Configuration();

        //能夠手動添加指定的配置文件

//        conf.addResource("my-core-site.xml");

//經過conf的configuration對象建立了該分佈式文件系統fs,默認若是不指定文件的話爲本地文件系統

        FileSystem fs = FileSystem.get(conf);

        //定義一個URL的字符串

        String file = "hdfs://hadoop01/user/hadoop/data2/demo.txt";

        //經過一個URL的字符串構建一個path對象,其實就是文件的地址

        Path path = new Path(file);

        //獲得制定路徑下面的文件的狀態

        FileStatus st = fs.getFileStatus(path);

        System.out.println("st.getBlockSize() = " + st.getBlockSize());

        System.out.println("st.getAccessTime() = " + st.getAccessTime());

        System.out.println("st.getGroup() = " + st.getGroup());

        System.out.println("st.getLen() = " + st.getLen());

        System.out.println("st.getModificationTime() = " + st.getModificationTime());

        System.out.println("st.getOwner() = " + st.getOwner());

        System.out.println("st.getReplication() = " + st.getReplication());

        System.out.println("st.getClass() = " + st.getClass());

        System.out.println("st.getPath() = " + st.getPath());

        System.out.println("st.getPermission() = " + st.getPermission());

        System.out.println("-----------------------------------");

//        System.out.println("st.getSymlink() = " + st.getSymlink());

        //獲得指定文件狀態的塊位置信息集合

        //把整個文件從0字節開始到整個文件的全長的字節

        BlockLocation[] locations = fs.getFileBlockLocations(st, 0, st.getLen());

        for(BlockLocation block : locations){

        System.out.println(block.getLength());

        System.out.println(block.getOffset());

        System.out.println(block.getCachedHosts());

        System.out.println(block.getHosts());

        System.out.println(block.getNames());

        System.out.println(block.getTopologyPaths());

        }

   }

}

相關文章
相關標籤/搜索