1. 程式人生 > >HDFS Java 客戶端使用(Windows開發環境)

HDFS Java 客戶端使用(Windows開發環境)

1.加入依賴

<dependency>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-client</artifactId>
          <version>2.6.4</version>
</dependency> 

2.檔案上傳到HDFS

/**
	 * @TODO 上傳檔案到HDFS
	 */
	@Test
	public void testAddFileToHdfs() throws Exception{
		// 要上傳的檔案所在的本地路徑
		Path src= new Path("F:\\staday-video.avi");
		// 要上傳到hdfs的目標路徑
		Path dst= new Path("/test_dir/");
		if(!fs.exists(dst))fs.mkdirs(dst);
		try {
			fs.copyFromLocalFile(src, dst);
			fs.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}

3.從HDFS中下載檔案到本地

/**
	 * @TODO 從HDFS中下載檔案到本地
	 */
	@Test
	public void testDownloadFileToLocal() throws Exception{
		fs.copyToLocalFile(
				false,//是否刪除原檔案
				new Path("/test_dir/staday-video.avi"),//源路徑
				new Path("e:/"),//目標路徑
				true //目標路徑是否本地檔案系統
				);
		fs.close();
	}

4.建立目錄、刪除目錄/檔案、重新命名 目錄/檔案

@Test
	public void testMkdirAndDeleteAndRename() throws IllegalArgumentException, IOException {

		
		// 建立目錄
		fs.mkdirs(new Path("/test_new/a1/b1"));

		// 刪除資料夾 ,如果是非空資料夾,引數2必須給值true
		fs.delete(new Path("/aaa"), true);

		// 重新命名檔案或資料夾
		fs.rename(new Path("/test_new"), new Path("/test_n"));

	}

5.檢視目錄資訊,只顯示檔案

/**
	 * 檢視目錄資訊,只顯示檔案
	 * 
	 * @throws IOException
	 * @throws IllegalArgumentException
	 * @throws FileNotFoundException
	 */
	@Test
	public void testListFiles() throws FileNotFoundException, IllegalArgumentException, IOException {
		RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/"), true);
		while (listFiles.hasNext()) {
			LocatedFileStatus fileStatus = listFiles.next();
			System.out.println(fileStatus.getPath().getName());
			System.out.println(fileStatus.getBlockSize());
			System.out.println(fileStatus.getPermission());
			System.out.println(fileStatus.getLen());
			BlockLocation[] blockLocations = fileStatus.getBlockLocations();
			for (BlockLocation bl : blockLocations) {
				System.out.println("block-length:" + bl.getLength() + "--" + "block-offset:" + bl.getOffset());
				String[] hosts = bl.getHosts();
				for (String host : hosts) {
					System.out.println(host);
				}
			}
			System.out.println("--------------列印的分割線--------------");
		}
	}

6.上述例子的demo工程下載

  hadoop-hdfs-test-master