五、 java使用其hdfs实例
1. 得到分布式系统实例
|
//的分布式文件系统实例 FileSystem fs = null; String url = "hdfs://localhost:9000"; Configuration config = new Configuration(); config.set("fs.default.name", url); fs = FileSystem.get(config); |
2. 目录管理实例
|
//得到其工作目录 Path workDir = fs.getWorkingDirectory(); String dir = workDir + "/" + dirName; //目录的路径 Path src = new Path(dir); //新建目录 fs.mkdirs(src); //删除目录 fs.delete(src, true); //移动目录 fs.rename(Path src, Path dst) //判断是不是目录 listStatus(Path f) 状态是目录还是物理文件 |
3. 上传文件
|
/** * 上传目录或文 * * @param fs * @param local * @param remote */ public synchronized static void upload(FileSystem fs, String local, String remote) { // Path home = fs.getHomeDirectory(); Path workDir = fs.getWorkingDirectory(); Path dst = new Path(workDir + "/" + remote); Path src = new Path(local); try { fs.copyFromLocalFile(false, true, src, dst); } catch (Exception e) { e.printStackTrace(); } } |
4. 下载文件
|
/** * 下载目录或文 * * @param fs * @param local * @param remote */ public synchronized static void download(FileSystem fs, String local, String remote) { // Path home = fs.getHomeDirectory(); Path workDir = fs.getWorkingDirectory(); Path dst = new Path(workDir + "/" + remote); Path src = new Path(local); try { fs.copyToLocalFile(false, dst, src); } catch (Exception e) { } } |
