大数据技术原理与应用实验五

实验:五

实验题目:熟悉常用的HDFS操作-利用Java API编程实现

1.实验目的

· 熟悉HDFS操作常用的Java API。

2.实验平台

· Hadoop 2.7.1

· Eclipse

· jdk

3.实验内容

· 在eclipse软件(或者其他Java IDE),使用java 语言编写能实现下面功能的程序:

  1. 在hdfs上,创建新文件夹 如 input。

  2. 从本地系统上传一个文件txt 文件到hdfs上

  3. 读取刚上传的文件的内容

  4. 对刚读取的文件写入内容

4、实验要求:

(1) 程序要添加适当的注释,规范写代码;

(2) 运行代码并且附加打印的结果和图片;

(3) 根据实验报告模板详细书写实验报告;

代码实现:

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;

public class HDFSDemo04 {
	
	public static void MkDirs() throws IOException {
		String uri = "hdfs://itcast01:8000";
		Configuration conf = new Configuration();
		FileSystem fs = FileSystem.get(URI.create(uri), conf);
		boolean res = fs.mkdirs(new Path("/input"));
		System.out.println(res==true?"Success":"Fail");
	}
	
	
	public static void copyLocToHdfs() throws IOException {
		Configuration conf = new Configuration();
		conf.set("fs.defaultFS","hdfs://itcast01:8000");
		FileSystem fs = FileSystem.get(conf);
		Path src = new Path("D:\\英雄时刻\\data.txt");
		Path dst = new Path("/input");
		fs.copyFromLocalFile(src, dst);
	}
	
	
	public static void GetContent() throws IOException {
		Configuration conf = new Configuration();
		conf.set("fs.defaultFS","hdfs://itcast01:8000");
		FileSystem fs = FileSystem.get(conf);
		FSDataInputStream fsDataInputStream = fs.open(new Path("/input/data.txt"));
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		IOUtils.copyBytes(fsDataInputStream, stream, 1024);
		System.out.println("haha~"+new String(stream.toByteArray()));
	}
	
	
	public static void WriteCont() throws IOException {
		Configuration conf = new Configuration();
		conf.set("fs.defaultFS","hdfs://itcast01:8000");
		FileSystem fs = FileSystem.get(conf);
		byte[] file_content = "\nThis is az!\n".getBytes();
		FSDataOutputStream fsDataOutputStream = fs.create(new Path("/input/data.txt"));
		fsDataOutputStream.write(file_content);
	}
	
	
	public static void main(String[] args) throws IOException {
		//MkDirs();
		//copyLocToHdfs();
		//GetContent();
		WriteCont();
	}
	
	
}

实验截图:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

发布了80 篇原创文章 · 获赞 69 · 访问量 8935

猜你喜欢

转载自blog.csdn.net/qq_43437122/article/details/105140060