java操作hdfs

来源:互联网 发布:创业公司取名 知乎 编辑:程序博客网 时间:2024/05/22 22:33
import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.URI;import java.net.URISyntaxException;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.FileSystem;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.IOUtils;import org.junit.Before;import org.junit.Test;public class HDFSDemo {    FileSystem fs = null;    @Before    public void init() throws IOException, URISyntaxException, InterruptedException{        /**         * 使用和hdfs系统上具有写权限的用户,伪装成root,否则是本机用户,可能没有写权限         * 这样没有安全性,关于hadoop的安全参考网络资源         */        fs = FileSystem.get(new URI("hdfs://ubuntu:9000"), new Configuration(),"root");    }    @Test    public void testUpload() throws IllegalArgumentException, IOException{        /**         * 读取本地系统文件         */        InputStream in =new FileInputStream("F://ngrok.exe");        /**         * 在hdfs上创建一个文件         */        OutputStream out = fs.create(new Path("/ngrok"));        /**         * 输入-->输出         */        IOUtils.copyBytes(in, out, 4096, true);    }    @Test    public void testDownload() throws IllegalArgumentException, IOException{        fs.copyToLocalFile(new Path("/ngrok"), new Path("f://ngrok"));    }    @Test    public void testDelete() throws IllegalArgumentException, IOException{        fs.delete(new Path("/ngrok"), false);    }    @Test    public void testMkdir() throws IllegalArgumentException, IOException{        fs.mkdirs(new Path("/test11"));    }    public static void main(String[] args) throws IOException, URISyntaxException  {        FileSystem fs = FileSystem.get(new URI("hdfs://ubuntu:9000"), new Configuration());        //打开hdfs文件,获取输入流        InputStream in = fs.open(new Path("/test"));        OutputStream out = new FileOutputStream("F://test");        IOUtils.copyBytes(in, out, 4096, true);    }}
0 0