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