##直接粘代码
public class HDFSTest {
public static final String HDFS_PATH="hdfs://hadoop001:9000";
public static final String HADOOP_NAME="hadoop";
Configuration configuration=null;
FileSystem fs=null;
@Before
public void setUp() throws Exception{
//可以使用configuration对象设置hdfs.site.xml文件中的属性值
//configuration.set("dfs.replication","1");
configuration = new Configuration();
fs = FileSystem.get(new URI(HDFS_PATH), configuration,HADOOP_NAME);
}
@After
public void close()throws Exception{
fs.close();
}
//从HDFS上下载指定块的数据,比如刚上传的那个数据,分为3个数据块,我们一个个下载,先下载第一个Block0的数据,然后下载后看能否在windows上组装起来
@Test
public void copyToLocalIO() throws Exception{
FSDataInputStream in = fs.open(new Path("/cdh-tar/hadoop-2.6.0-cdh5.7.0.tar.gz"));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File("C:\\Users\\yoohh\\Desktop\\hadoop01.part0")));
byte[] buffer = new byte[1024];
//这样使用for循环就能手动控制要读取的数据块,比如这个就是读取第一块数据块Block0的数据
for(int i=0;i<1024*128;i++){
//从输入流中将数据读入到buffer中
in.read(buffer);
//再从buffer中将数据写入输出流中
out.write(buffer);
}
IOUtils.closeStream(out);
IOUtils.closeStream(in);
}
//从HDFS上下载指定块的数据,比如刚上传的那个数据,分为3个数据块,我们一个个下载,现在下载第二个Block1的数据,然后下载后看能否在windows上组装起来
@Test
public void copyToLocalIO1() throws Exception{
FSDataInputStream in = fs.open(new Path("/cdh-tar/hadoop-2.6.0-cdh5.7.0.tar.gz"));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File("C:\\Users\\yoohh\\Desktop\\hadoop01.part1")));
//使用seek方法跳过第一个块,读取第二个Block1的数据
in.seek(1024*1024*128);
byte[] buffer = new byte[1024];
//这样使用for循环就能手动控制要读取的数据块,比如这个就是读取第二块数据块Block1的数据
for(int i=0;i<1024*128;i++){
//从输入流中将数据读入到buffer中
in.read(buffer);
//再从buffer中将数据写入输出流中
out.write(buffer);
}
IOUtils.closeStream(out);
IOUtils.closeStream(in);
}
//从HDFS上下载指定块的数据,比如刚上传的那个数据,分为3个数据块,我们一个个下载,现在下载第三个Block2的数据,然后下载后看能否在windows上组装起来
@Test
public void copyToLocalIO2() throws Exception{
FSDataInputStream in = fs.open(new Path("/cdh-tar/hadoop-2.6.0-cdh5.7.0.tar.gz"));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File("C:\\Users\\yoohh\\Desktop\\hadoop01.part2")));
//使用seek方法跳过第一个和第二个数据块,读取第三个Block2的数据,这里要 * 2
in.seek(1024*1024*128*2);
IOUtils.copyBytes(in,out,configuration);
IOUtils.closeStream(out);
IOUtils.closeStream(in);
}
//然后在windows使用type命令将三个文件组合在一起
//C:\Users\yoohh\Desktop>type hadoop01.part2 >> hadoop01.part0
//C:\Users\yoohh\Desktop>type hadoop01.part1 >> hadoop01.part0
//最后将 hadoop01.part0再改名为 hadoop-2.6.0-cdh5.7.0.tar.gz 发现大小跟之前一样,也可以正常解压,没有丢失
}
}
javaAPI操作HDFS进行文件流传输
最新推荐文章于 2024-05-12 15:42:36 发布