Hadoop權威指南:通過FileSystem API讀取數據
在Hadoop中,FileSystem是一個通用的文件系統API
獲取FileSystem實例的幾個靜態方法
public static FileSystem get(Configureation conf) throws IOExceptionpublic static FileSystem get(URI uri, Configureation conf) throws IOExceptionpublic static FileSystem get(URI uri, Configuration conf, String user) throws IOException
Configuration對象封裝了客戶端或服務器的配置,通過設置配置文件讀取類路徑來實現
- 第一種方法返回的是默認文件系統(在core-site.xml中指定, 如果沒有指定則為默認)
- 第二種方法通過給定的URI方案和權限來確定要使用的文件系統,如果給定URI中沒有指定方案,則返回默認文件系統
- 第三種方法,給定用戶來訪問文件系統,對安全來說至關重要
獲取本地文件系統的運行實例
使用getLocal()方法獲取本地文件系統的運行實例
public static LocalFileSystem getLocal(Configuration conf) throws IOException
獲取文件輸入流
有了FileSystem實例之后,調用open()函數來獲取文件的輸入流
public FSDataInputStream open(Path f) throws IOExceptionpublic abstract FSDataInputStream open(Path f, int bufferSize) throws IOException
第一種方法默認緩沖區大小為4kb
實現
源文件名
FileSystemCat.java
代碼
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
public class FileSystemCat {
public static void main(String[] args) throws IOException {
String uri = args[0];
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(uri), conf);
InputStream in = null;
try {
in = fs.open(new Path(uri));
IOUtils.copyBytes(in, System.out, 4096, false);
} finally {
IOUtils.closeStream(in);
}
}
}
編譯
javac FileSystemCat.java
運行
hadoop FileSystemCat hdfs://localhost:9000/user/hadoop/in.txt
