hadoop 提供了一个org.apache.hadoop.fs.FileSystem 类,该类负责对HDFS进行操做
public static final String HADOOP_PATH="hdfs://hadoop:9000"; public static final String DIR_PATH="/love"; public static final String FILE_PATH="/love/you.txt"; static FileSystem fileSystem=null; public static final void main(String[] args)throws Exception{ fileSystem=FileSystem.get(new URI(HADOOP_PATH),new Configuration()); //上传文件夹(建立文件夹) //上传文件 //下载文件 //删除文件或者文件夹 }
public static void mkdir(FileSystem fileSystem) throws IOException { fileSystem.mkdirs(new Path(DIR_PATH)); }
Note: FileSystem.mkdirs(Path) 在HDFS上建立文件夹 返回一个boolean值java
public static void upload(FileSystem fileSystem) throws IOException, FileNotFoundException { final OutputStream out=fileSystem.create(new Path(FILE_PATH)); final FileInputStream in=new FileInputStream("you.txt"); IOUtils.copyBytes(in, out, 1024, true); }
Note: FileSystem.create(Path path) 在HDFS上建立一个文件,而后返回这个文件的输出流,把咱们想上传的文件与HDFS上文件的输出流对接达到上传的文件的效果apache
public static void downLoadData(FileSystem fileSystem) throws IOException { FSDataInputStream inFile = fileSystem.open(new Path(FILE_PATH)); IOUtils.copyBytes(inFile, System.out, 1024, true); }
Note:FileSystem.open(Path path);打开HDFS上的一个文件,而后获得这个文件的输入流,拿到这个文件的输入流了以后,就能够作下载操做了oop
public static void deleteFileOrDrictory(FileSystem fileSystem) throws IOException { fileSystem.delete(new Path(FILE_PATH), true); }
Note: FileSystem.delete(Path path,boolean recursive) 该方法是对HDFS上得文件或目录作删除操做,spa
一下是该方法的一些注释:code
/** Delete a file. * * @param f the path to delete. * @param recursive if path is a directory and set to * true, the directory is deleted else throws an exception. In * case of a file the recursive can be set to either true or false. * @return true if delete is successful else false. * @throws IOException */
大体的意思是说,若是删除文件,那么第二个boolean参数能够是true也能够是false,若是删除的是目录的时候必须为true,删除不成功报IOExceptionhadoop