用程式對hdfs進行操作。

來源:互聯網
上載者:User

標籤:通過程式串連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進行操作。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.