大数据之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);
        }
    }
}

运行结果:
在这里插入图片描述

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