一、HDFS java經常使用API 及hadoop-eclipse-plugin-1.1.2.jar插件的使用java
import java.io.FileInputStream; import java.net.URI; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IOUtils; public class BasicOperation { private static final String PATH="hdfs://192.168.255.132:9000/"; /** * @param args * @throws Throwable * @author nwpulisz */ public static void main(String[] args) throws Throwable { // TODO Auto-generated method stub URI uri = new URI(PATH); FileSystem fileSystem = getFileSystem(uri); list(fileSystem,PATH); readFileFromServer(fileSystem,PATH+"hello"); //putFiletoServer(fileSystem, PATH+"up.txt"); //mkdirOnServer(fileSystem,PATH+"Yang" ); //rmdirOnServer(fileSystem, PATH+"Li"); } private static FileSystem getFileSystem(URI uri) throws Throwable{ //獲取FileSystem對象,FileSystem的獲取方式:不能new,只能經過靜態方法獲取; FileSystem fileSystem = FileSystem.get(uri, new Configuration()); return fileSystem; } private static void readFileFromServer(FileSystem fileSystem,String path) throws Throwable{ //讀取服務器上的文件 FSDataInputStream openStream = fileSystem.open(new Path(path)); IOUtils.copyBytes(openStream, System.out, new Configuration());//把文件流複製到輸出流,控制檯輸出 IOUtils.closeStream(openStream); } private static void putFiletoServer(FileSystem fileSystem,String path) throws Throwable{ //上傳本地文件至服務器 FSDataOutputStream openStream = fileSystem.create(new Path(path)); FileInputStream fileInputStream = new FileInputStream("up.txt"); //把本地文件up.txt轉換爲輸入流 IOUtils.copyBytes(fileInputStream, openStream, new Configuration()); IOUtils.closeStream(fileInputStream); } private static void mkdirOnServer(FileSystem fileSystem,String path) throws Throwable{ //建立目錄 fileSystem.mkdirs(new Path(path)); } private static void rmdirOnServer(FileSystem fileSystem,String path) throws Throwable{ //刪除目錄或者文件均可以 fileSystem.delete(new Path(path),true); } private static void list(FileSystem fileSystem,String path) throws Throwable{ //列出對應路徑下的目錄文件 FileStatus[] listStatus = fileSystem.listStatus(new Path(path)); for(FileStatus fileStatus:listStatus){ String isDir = fileStatus.isDir()?"目錄":"文件"; String name = fileStatus.getPath().getName(); System.out.println(isDir+"\t"+name); } } }