本地多級文件 原樣上傳到hdfs

package com.hdfs;


import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocalFileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;


import com.beicai.utils.MyUtils;
/**
 * 
 * @described 本地多級文件 原樣上傳到hdfs
 */
public class HdfsWork {


public static void main(String[] args) throws Exception {
myMerge();
System.out.println("ok");
}

public static void myWrite(Path path,LocalFileSystem lfs,FileSystem fs) throws Exception{
FileStatus[] fst = lfs.listStatus(path);
for(int i=0;i<fst.length;i++){
Path dir = fst[i].getPath();//獲取路徑
//file:/D:/data/a
dir = new Path(dir.toString().split(":")[2]);//截取相對本地磁盤D盤的絕對路徑

if(fst[i].isDirectory()){//是文件夾

myWrite(fst[i].getPath(),lfs,fs);//調用本身
fs.mkdirs(dir);//創建裏面沒有文件的文件夾(空文件夾)
} else {
FSDataInputStream fsdis = lfs.open(fst[i].getPath()); //打開文件輸入流
FSDataOutputStream fsdos = fs.create(dir);//打開文件輸出流流

int read = 0;
byte[] buffer = new byte[255];
while((read=fsdis.read(buffer))>0){
fsdos.write(buffer, 0, read);
}

IOUtils.closeStream(fsdis);//關閉流
IOUtils.closeStream(fsdos);
}
}
}

public static void myMerge() throws Exception{
FileSystem fs = MyUtils.getFileSystem();
LocalFileSystem lfs = MyUtils.getLocalFileSystem();
Path localPath = new Path("D:/datas");//本地路徑


myWrite(localPath,lfs,fs);//調用方法
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章