用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();
}