標籤:style stream bigdata stat dfs write utils ethos factor
1.下載檔案到本地
public class HdfsUrlTest {
static{
//註冊url 讓java程式識別hdfs的url
URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
}
public static void main(String[] args) {
InputStream in = null;
OutputStream out = null;
try {
String file = "hdfs://hadoop-yarn.test.com:8020/user/testi/conf/core-site.xml";
URL fileUrl = new URL(file);
in = fileUrl.openStream();
out = new FileOutputStream(new File("d:/core-site.xml"));
//下載檔案到本地
IOUtils.copyBytes(in,out,4096, false);
} catch (Exception e) {
e.printStackTrace();
}finally{
IOUtils.closeStream(in);}}}
2.查看叢集資訊
public static void cluserStatus() throws Exception{
FileSystem fs = HdfsUtil.getFs();
DistributedFileSystem dfs = (DistributedFileSystem)fs;
FsStatus fss = dfs.getStatus();
DatanodeInfo[] datanodeInfos = dfs.getDataNodeStats();
for(DatanodeInfo datanodeinfo : datanodeInfos){
System.out.println(datanodeinfo.getHostName());}}
3.建立一個檔案夾
public void testHDFSMkdir() throws Exception{
String hdfsUrl = "hdfs://192.168.10.11:8020";
Configuration conf= new Configuration();
FileSystem fs = FileSystem.get(URI.create(hdfsUrl),conf);
Path path = new Path("/bigdata");
fs.mkdirs(path);}
4.建立一個檔案
public void testCreateFile() throws Exception{
String hdfsUrl = "hdfs://192.168.10.11:8020";
Configuration conf= new Configuration();
FileSystem fs = FileSystem.get(URI.create(hdfsUrl),conf);
Path path = new Path("/bigdata/a.txt");
FSDataOutputStream out = fs.create(path);
out.write("hello hadoop".getBytes());}
5.檔案重新命名
public void testRenameFile() throws Exception{
String hdfsUrl = "hdfs://192.168.10.11:8020";
Configuration conf= new Configuration();
FileSystem fs = FileSystem.get(URI.create(hdfsUrl),conf);
Path path = new Path("/bigdata/a.txt");
Path newPath = new Path("/bigdata/b.txt");
System.out.println(fs.rename(path, newPath));}
6.上傳檔案
public static void write() throws Exception{
FileSystem fs = HdfsUtil.getFs();
OutputStream outStream = fs.create(new Path("/user/lcc/conf/put-core-site.xml"));
FileInputStream inStream = new FileInputStream(new File("d:/core-site.xml"));
IOUtils.copyBytes(inStream, outStream, 4096, true);}
Hadoop程式想讀取hdfs中的資料,最簡單的方法是使用java的URL對象開啟一個資料流,並從中讀取資料。
需要一個fsUrlStreamHandlerFactory執行個體調用set過的一個URL,這種方法java虛擬機器只能調用一次,缺點是如果程式的其他部分也設定了這個,會導致無法再從hadoop中讀取資料。
新方法,需要使用filesystem的api開啟一個檔案的輸入資料流。
檔案在hadoop檔案系統中被視為一個hadoop path對象,把一個檔案夾或檔案路徑看做為一個hadoop檔案系統的URL。
三種方法。
Get(conf)和get(uri,conf),newInstance
hdfs常用api(java)