Hadoop學習--通過API得到文件系統狀態--day04

import java.io.ByteArrayOutputStream;

import java.io.InputStream;

import java.net.URL;


import org.apache.hadoop.conf.Configuration;

import org.apache.hadoop.fs.BlockLocation;

import org.apache.hadoop.fs.FSDataInputStream;

import org.apache.hadoop.fs.FileStatus;

import org.apache.hadoop.fs.FileSystem;

import org.apache.hadoop.fs.FsUrlStreamHandlerFactory;

import org.apache.hadoop.fs.Path;

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());

        }

   }

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章