用java代碼實作Linux下的指令
通過FileSystem對象操作,實作setup()和test()函數
@Before
public void setup() throws URISyntaxException, IOException, InterruptedException {
fs=FileSystem.get(new URI("hdfs://192.168.234.132:8020"),new Configuration(),"hr");
}
常用方法:
1.按照指定路徑建立檔案(可以級聯):create(Path f)
2.按照指定路徑建立檔案夾(可以級聯):mkdirs(Path f)
3.删除指定檔案或檔案夾
delete(Path path,boolean recursive) recursive指定是否遞歸删除,删除非空檔案夾時必須指定為true。
4.上傳檔案到HDFS:
copyFromLocalFile(Path src,Path dst)
copyFromLocalFile(boolean delSrc,Path src,Path dst) delSrc指定上傳完成後是否删除源檔案
copyFromLocalFile(boolean delSrc,boolean overwrite,Path src,Path dst) overwrite指定若檔案已存在是否覆寫
copyFromLocalFile(boolean delSrc,boolean overwrite,Path[] srcs,Path dst) 一次上傳多個檔案
注意這個local,如果是在windows上測試,local指的就是windows本地
moveFromLocalFile(Path src,Path dst) 上傳檔案到HDFS系統,并且完成之後自動删除源檔案
moveFromLocalFile(Path[] srcs,Path dst)
5.從HDFS上下載下傳檔案:
copyToLocalFile(Path src,Path dst)
copyToLocalFile(boolean delSrc,Path src,Path dst)
moveToLocalFile(Path src,Path dst) 從HDFS上下載下傳檔案,并且完成之後自動删除源檔案
6.判斷是否是檔案夾:isDirectory(Path f)
7.判斷是否是檔案:isFile(Path f)
8.列出檔案(相當于Linux下的ls,但不顯示檔案夾):
listFiles(Path f,boolean recursive) 傳回的是LocatedFileStatus的疊代器
RemoteIterator<LocatedFileStatus> lfs=fs.listFiles(new Path("/kinggsoft"),true);
while(lfs.hasNext())
{
System.out.println(lfs.next().getPath());
}
9.以流的方式讀取檔案:
open(Path f) 傳回FSDataInputStream
public void test() throws IOException {
FSDataInputStream fsis=fs.open(new Path("/mobile2"));
byte[] temp=new byte[128];
int len=-1;
while((len=fsis.read(temp))!=-1)
{
System.out.println(new String(temp,0,len));
}
}
10.向檔案中追加内容:
append(Path f) 傳回FSDataOutputStream
public void appendToFile() throws IOException {
FSDataOutputStream fsos=fs.append(new Path("/mobile2"));
fsos.write("hahaha".getBytes());
fsos.close();
}