大數據之Hadoop學習(四)基於JAVA的HDFS文件操作(擴展實驗2)

一、先啓動Hadoop

./sbin/start-dfs.sh

出現以下界面說明啓動成功
在這裏插入圖片描述

二、編程實現一個類“MyFSDataInputStream”,該類繼承“org.apache.hadoop.fs.FSDataInputStream”,要求如下:實現按行讀取HDFS中指定文件的方法“readLine()”,如果讀到文件末尾,則返回空,否則返回文件一行的文本。

1.代碼如下:

package test2;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.io.*;
public class MyFSDataInputStream extends FSDataInputStream {
	public MyFSDataInputStream(InputStream in) {
		super(in);
	}
	/** 
		*實現按行讀取
		*每次讀入一個字符,遇到"n"結束,返回一行內容
		*/
	public static String readline(BufferedReader br) throws IOException {
		char[] data = new char[1024];
		int read = -1;
		int off = 0; //循環執行時,br每次會從上- -次讀取結束的位置繼續讀取,因此該函數裏,off每次都從0開始
		while ( (read = br.read(data, off, 1)) != -1 ) {
			if (String.valueOf(data[off]).equals("\n") ) {
			off += 1;
			break;
			}		
			off += 1;
		}
		if (off> 0) {
			return String.valueOf( data);
		} else {
		return null;
		}
	}
	/** 
		*讀取文件內容
		*/
		public static void cat(Configuration conf, String remoteFilePath) throws IOException {
			FileSystem fs = FileSystem.get(conf);
   			Path remotePath = new Path(remoteFilePath);
			FSDataInputStream in = fs.open(remotePath);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String line = null;
			while ( (line = MyFSDataInputStream.readline(br)) != null ) {
				System.out.println(line);
			}
			br.close();
			in.close();
			fs.close();
		}
	/** 
	 *主函數
	 */
	public static void main(String[] args) {
		Configuration conf = new Configuration();
		conf.set(" fs.default.name", "hdfs://localhost:9000");
		String remoteFilePath = "/user/hadoop/file/text.txt"; // HDFS路徑
		try {
			MyFSDataInputStream.cat(conf,remoteFilePath);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


2.運行結果:

在這裏插入圖片描述

三、查看Java幫助手冊或其它資料,用”java.net.URL”和“org.apache.hadoop.fs.FsURLStreamHandlerFactory”編程完成輸出HDFS中指定文件的文本到終端中。

1.代碼如下:

package test2;

import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;
import java.io.*;
import java.net.URL;

public class HDFSApi {
    static {
        URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
    }

    /**
     * 主函數
     */
    public static void main(String[] args) throws Exception {
    	
        String remoteFilePath = "hdfs://localhost:9000/user/hadoop/file/text.txt"; // HDFS 文件
        InputStream in = null;
        try {
            /* 通過 URL 對象打開數據流,從中讀取數據 */
            in = new URL(remoteFilePath).openStream();
            IOUtils.copyBytes(in, System.out, 4096, false);
        } finally {
            IOUtils.closeStream(in);
        }
    }
}

運行結果:
在這裏插入圖片描述

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