標籤:
訪問hdfs上的檔案並寫出到輸出台
/** * 訪問hdfs上的檔案並寫出到輸出台 * @param args */ public static void main(String[] args) { try { //將hdfs格式的url轉換成系統能夠識別的 URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory()); URL url = new URL("hdfs://hadoop1:9000/hello"); InputStream in = url.openStream(); /** * 將讀取到的資料寫入到檔案,不需要自己控制緩衝區,也不需要自己去讀取輸入資料流 * @param in 輸入資料流 * @param out 輸出資料流 * @param bufferSize 換成區大小 * @param close 是否關閉流,如果是false,需要在finally中關閉 * IOUtils.closeStream(in); */ IOUtils.copyBytes(in, System.out, 1024, true); } catch (Exception e) { e.printStackTrace(); } }擷取FileSystem
/** * 擷取FileSystem * 使用Hadoop的fileSystem讀取檔案 */ public static FileSystem getFileSystem() throws IOException, URISyntaxException { FileSystem fileSystem = FileSystem.get(new URI("hdfs://hadoop1:9000"), new Configuration()); return fileSystem; }建立檔案夾
/** * 建立檔案夾 * @throws URISyntaxException */ public static void mkdir() throws IOException, URISyntaxException { FileSystem fileSystem = getFileSystem(); //在hdfs上建立檔案夾,並返回建立是否成功的標示 boolean successful = fileSystem.mkdirs(new Path("/dir1")); if(successful){ System.out.println("建立檔案夾成功"); } }上傳
/** * 上傳 * @throws URISyntaxException */ public static void putdata() throws IOException, FileNotFoundException, URISyntaxException { FileSystem fileSystem = getFileSystem(); //建立一個上傳路徑,返回輸出資料流 FSDataOutputStream os = fileSystem.create(new Path("/dir1/readme")); FileInputStream in = new FileInputStream("D:\\Program Files\\others\\2345Soft\\HaoZip\\2345好壓免責聲明.txt"); IOUtils.copyBytes(in, os, 1024, true); }下載
/** * 下載 * @throws URISyntaxException */ public static void download() throws IOException, URISyntaxException { FileSystem fileSystem = getFileSystem(); FSDataInputStream in = fileSystem.open(new Path("hdfs://hadoop1:9000/hello")); //關閉流需要手動關閉,System.out也是一個輸出資料流,如果是true 下面就不會輸出了 IOUtils.copyBytes(in, System.out, 1024, false); in.close(); }刪除檔案或檔案夾
/**刪除檔案或檔案夾 * true:表示是否遞迴刪除,如果是檔案,這裡是true,false都是無所謂, * 檔案夾必須是true,否則報錯 * @throws URISyntaxException */ public static void delete() throws IOException, URISyntaxException { FileSystem fileSystem = getFileSystem(); boolean isDeleted = fileSystem.delete(new Path("/dir1"), true); if(isDeleted){ System.out.println("刪除成功"); } }遍曆目錄
/**遍曆目錄 * 調用FileSystem的listStatus方法 * 查看file的狀態 使用FileStatus * @throws URISyntaxException */ public static void list() throws IOException, URISyntaxException { FileSystem fileSystem = getFileSystem(); FileStatus[] listStatus = fileSystem.listStatus(new Path("/")); for (FileStatus fileStatus : listStatus) { String isDir = fileStatus.isDir()?"目錄":"檔案"; String name = fileStatus.getPath().getName().toString(); System.out.println(isDir+"-->"+name); } }
hadoop hdfs的java操作