/**
* 总结了HDFS的常见javaAPI操作,包括:
* 1.创建文件夹
* 2.删除文件夹
* 3.创建文件
* 4.上传文件
* 5.下载文件
* 6.使用seek命令多次重定位操作
* 7.多线程(并发)写入多个文件
* 8.文件的追加
* 9.多线程追加入单个文件;注:这种方式无法实现,示例中列出了错误原因
* 10.不同字符集文件的上传
* 11.hdfs内部文件拷贝
* @author SHCH
*
*/
public class HDFS_Demo1 {
public static void main(String[] args) throws Exception {
}
/**
* hdfs文件的内部拷贝,类似hdfs shell的distcp命令
* 但注意,只是拷贝文件
* 目前还没找到内部拷贝文件夹的api
*
* @throws IOException
*/
private static void innerHDFSFileCopy() throws IOException {
String path="hdfs://192.168.80.132:9000";
FileSystem fs=FileSystem.get(URI.create(path),new Configuration());
FSDataInputStream fdis = fs.open(new Path("/one/bb.xml"));
FSDataOutputStream fdos = fs.create(new Path("/one/cc.xml"));
//HDFS自身的拷贝
IOUtils.copyBytes(fdis, fdos, 1024, true);
}
/**
* 修改hdfs-site.xml,添加property,dfs.support.append并设置为true,可以实现文件的追加(hadoop1不支持),
*
*
* 下面这个方法会出错,如下:
* because DFSClient_NONMAPREDUCE_1373065962_11 is already the current lease holder.
* 意思是说多个并发线程不能写入同一个文件
*
* 注:此时文件有可能已经写入数据,但数据中只是一个线程写入的内容!!!
*/
private static void multiThreadWriteSingleFile() {
class MyRunnable implements Runnable {
private int idx;
public MyRunnable(int... idx) {
if (idx.length > 0)
this.idx = idx[0];
}
FileSystem fs = null;
@Override
public void run() {
try {
fs = FileSystem.get(URI.create("hdfs://192.168.80.132:9000"), new Configuration());
FSDataOutputStream fdos = fs.append(new Path("/one/appendfile"));
for (int k = 0; k < 5; k++) {
for (int i = 0; i < 5; i++) {
fdos.write(Thread.currentThread().getName().getBytes());
fdos.write(" ".getBytes());
}
fdos.write("\n".getBytes());
//不知道有啥用......
fdos.sync();
Thread.currentThread().sleep(100);// 让其它綫程执行一下