应用场景:
现有一个比较大的文件需要远程传输,但是因为文件比较大,在传输过程中会报错,因此,采用的方案是把大文件切割成一个个小文件,最后再进行合并!
我是通过一段Java代码把hdfs的一个500M文件下载到本地,生成两个文件,然后进行合并的。
代码如下:
@Test
public void download() throws IOException {
FSDataInputStream in = fileSystem.open(new Path("/hdfsapi2/hadoop-2.6.0-cdh5.16.2.tar.gz"));
FileOutputStream out = new FileOutputStream(new File("out/spark.tgz.part0"));
byte[] buffer = new byte[2048];
for (int i = 0;i<1024*1024*128/2048;i++){
in.read(buffer);
out.write(buffer);
}
IOUtils.closeStream(in);
IOUtils.closeStream(out);
}
@Test
public void download2() throws IOException {
FSDataInputStream in = fileSystem.open(new Path("/hdfsapi2/hadoop-2.6.0-cdh5.16.2.tar.gz"));
FileOutputStream out = new FileOutputStream(new File("out/spark.tgz.part1"));
byte[] buffer = new byte[2048];
in.seek(1024*1024*128);
IOUtils.copyBytes(in,out,fileSystem.getConf());
IOUtils.closeStream(in);
IOUtils.closeStream(out);
}
然后在本地打开cmd命令行
win+r
进入到对应的文件夹(我是在F盘,首先要执行命令 F: 进入到F盘中,才能切换目录!!!)
通过以下命令进行合并:
type spark.tgz.part1 >> spark.tgz.part0
将第二个文件块追加到第一个文件中。
然后,结束后,把第一个文件重新命名,准确的说是加一个 .gz的后缀,把这个文件变成压缩包。
之后在进行解压,就是原来的那个文件了,试试吧!