標籤:通過程式串連hdfs 用程式讀取hdfs上的檔案
調試加安裝了半天,怎麼也沒有配置好怎麼通過Eclipse直接連接hdfs,最後我還是打成一個jar包放到Linux虛擬機器中執行的。
執行命令Java -jar XXX.jar.
其中對hdfs的操作比較簡單,主要就FileSystem這一個類,這個東西搞懂了,你對通過程式進行對hdfs的操作自然而然的也就非常熟練了。
下面我簡單的舉一個簡單的從hdfs上讀取檔案內容的例子。大家分享一下。
package com.pzoom.hdfs;import java.io.BufferedInputStream;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 org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.FSDataInputStream;import org.apache.hadoop.fs.FileStatus;import org.apache.hadoop.fs.FileSystem;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.IOUtils;import org.apache.hadoop.util.Progressable;public class PutFileToHdfs { /** * 從HDFS上讀取檔案 */private static void readFromHdfs() throws FileNotFoundException,IOException {String dst = "hdfs://ubuntu:9000/";Configuration conf = new Configuration();FileSystem fs = FileSystem.get(URI.create(dst), conf);String path = "/README.txt";FSDataInputStream hdfsInStream = fs.open(new Path(path));IOUtils.copyBytes(hdfsInStream, System.out, conf, true);/*OutputStream out = new FileOutputStream("/home/chenlongquan/output");byte[] ioBuffer = new byte[1024];int readLen = hdfsInStream.read(ioBuffer);while (-1 != readLen) {out.write(ioBuffer, 0, readLen);readLen = hdfsInStream.read(ioBuffer);}out.close();hdfsInStream.close();fs.close();*/} /** * main函數 * * @param args * @throws Exception */public static void main(String[] args) throws Exception {try {//uploadToHdfs();readFromHdfs(); } catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} finally { }}}
用程式對hdfs進行操作。