<img src="https://img-blog.csdn.net/20150803145759823?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
<img src="https://img-blog.csdn.net/20150803145822627?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
/*
1、通过代码来操作HDFS
2、实现了下载、上传文件的功能
*/
public class HDFSDemo {
/*
1、通过代码来操作HDFS
2、实现了下载功能
*/
public static void main(String[] args) throws IOException, URISyntaxException {
//与master建立联系
FileSystem fs =FileSystem.get(new URI("hdfs://master:9000"), new Configuration());
//通过流方式读取HDFS中的文件,将文件读入到内存当中
InputStream in = fs.open(new Path("/user/guest/esri/xiaojson/xiao.json"));
//输出路径
OutputStream out = new FileOutputStream("D://xiao.json");
//工具类将in中的内容copy到out中,大师级默认都是4096
IOUtils.copyBytes(in, out, 4096, true);
}
/*
1、通过代码来操作HDFS
2、实现了下载功能,通过一句话实现下载
*/
@Test
public void testDownLoad() throws IllegalArgumentException, IOException{
fs.copyToLocalFile(new Path("/user/guest/esri/xiaojson/xiao.json"), new Path("D://xiao1.json"));
}
FileSystem fs = null;
@Before
public void init() throws IOException, URISyntaxException, InterruptedException{
//创建FileSystem的实现类 (工具类)与master建立联系
fs =FileSystem.get(new URI("hdfs://master:9000"), new Configuration(),"guest");
}
/*
1、通过代码来操作HDFS
2、实现了上传功能
*/
@Test
public void testUpload() throws IOException{
//读取本地文件系统的文件,返回输入流
InputStream in = new FileInputStream("D://xiao123.json");
//在HDFS上创建一个文件,返回输出流
OutputStream out = fs.create(new Path("/test.jar"));
//工具类将in中的内容copy到out中,大师级默认都是4096
IOUtils.copyBytes(in, out, 4096, true);
}
}