/** * @author root *测试hadoop hdfs 的客户端操作 *项目创建只需要导入hadoop的hadoop-2.7.3-bin\share\hadoop下面所有jar包就可以了 *也可以使用maven依赖 *hadoop-core */ public class TestHDFS { /** * hadoop URL */ public static final String BASE_URL = "hdfs://s0:9000"; /** *本地文件系统的目录 */ public static final String LOCAL_URL = "F:/soft/temp"; /** * hadoop目录的地址 */ public static final String h = "/user/root/input"; /** * 配置对象 */ public static Configuration conf; /** * hadoop分布式文件系统的抽象 * */ public static FileSystem fs; // 静态代码块初始化文件系统 static { conf = new Configuration(); try { fs = FileSystem.get(URI.create(BASE_URL),conf); } catch (IOException e) { System.out.println("there is error!"); e.printStackTrace(); } } /** * 测试创建文件 * @throws IllegalArgumentException * @throws IOException */ public void create() throws IllegalArgumentException, IOException { FSDataOutputStream dos = fs.create(new Path(h+"/4.txt"),true); dos.write("hello hdfs\n".getBytes()); System.out.println("create over"); } public void exists() throws IOException { // 测试文件是否存在 Path path = new Path(h+"/5.txt"); System.out.println(fs.exists(path)); // false path = new Path(h+"/4.txt"); System.out.println(fs.exists(path)); // true } public void mkdir() throws IOException{ Path path = new Path("user/root/test"); boolean isSucc = fs.mkdirs(path); if(isSucc)System.out.println("创建目录成功!"); } public void downloadAndUpload() throws IllegalArgumentException, IOException{ /* * 从hdfs上复制到本地文件系统 * 一开始使用copyToLocalFile(src,dst) 方法发生错误 * 后来发现要使用copyToLocalFile(boolean delSrc, Path src, Path dst, * boolean useRawLocalFileSystem) 方法,多的两个参数表示第一个表示是否删除源文件,最后一个表示当本地文件系统不存在时使用RawLocalFileSystem */ fs.copyToLocalFile(false,new Path("/user/root/output1/part-00000"), new Path("F:/soft/temp"),true); // 从本地文件系统复制到hdfs上 fs.copyFromLocalFile(new Path("F:/soft/temp/1.gz"), new Path("/user/root/ncdc_data")); } @Test public void input() throws IOException { String src = "G:/javaUtils/readme.txt"; InputStream in = new BufferedInputStream(new FileInputStream(src)); Path path = new Path(h+"/3.txt"); // 使用hadoop的FSDataOutputStream上传文件 // 对于大型文件还可以使用进度条显示进度 FSDataOutputStream out = fs.create(path, new Progressable() { @Override public void progress() { System.out.print(". "); } }); // hadoop的工具类 IOUtils.copyBytes(in, out, 4096,true); // . . 562 System.out.println(fs.getFileStatus(path).getLen()); } @Test public void deleteAndCreateNewFile() throws IllegalArgumentException, IOException{ // true表示需要递归删除 fs.delete(new Path("/user/root/output1"),true); Path path = new Path(h+"/5.txt"); // 这个方法与create相比仅仅多了一个,文件是否存在的判断如果存在就不会创建了 fs.createNewFile(path); // 文件追加 FSDataOutputStream out = fs.append(new Path("/user/root/input/5.txt")); out.write("\nappend some data to a exists file\n".getBytes()); out.flush(); out.close(); }