代码如下:
package hdfs;
import org.apache.hadoop.conf.Configuration;
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.Path;
public class HDFSFileMeger {
/**
*
* @param srcFiles 要合并的源文件
* @param targetFile 目标文件
* @throws Exception
*/
public static void fileMeger(String srcFiles,String targetFile) throws Exception{
Configuration conf=new Configuration();
//conf.addResource(new Path("home/xm/hadoop-2.7.1/etc/hadoop/core-site.xml"));
FileSystem localFs=FileSystem.getLocal(conf);//获取本地系统
FileSystem tarFs=FileSystem.get(conf);//获取HDFS文件系统
Path localPath=new Path(srcFiles);//获取本地文件路径
Path targetPath=new Path(targetFile);//获取hdfs文件路径
FileStatus[] fileStatus=localFs.listStatus(localPath);//本地系统中指定的所有的目录
FSDataOutputStream dataOutputStream=tarFs.create(targetPath);//打开 中的输出流
for(FileStatus status:fileStatus){//遍历本地文件中所有的目录
Path path=status.getPath();
System.out.println("文件为:"+path.getName());
FSDataInputStream dataInputStream=localFs.open(path);//打开文件的输入流
byte[] buffer=new byte[1024];
int len=0;
while((len=dataInputStream.read(buffer))>0){
dataOutputStream.write(buffer, 0, len);
}
dataInputStream.close();
}
dataOutputStream.close();
}
public static void main(String[] args) throws Exception{
String l = "/home/xm/a/";
String f = "hdfs://master:9000/input/input1.txt";
fileMeger(l,f);
}
}
如果出现
Exception in thread "main" java.lang.IllegalArgumentException: Wrong FS: hdfs://master:9000/input
那么请参照
亲测可用:HDFS错误修改