我想读取文件路径,无论它们是 HDFS 还是本地文件。目前,我通过前缀为 file://的本地路径和前缀为 hdfs://的 HDFS 路径并编写如下代码
Configuration configuration = new Configuration();
FileSystem fileSystem = null;
if (filePath.startsWith("hdfs://")) {
fileSystem = FileSystem.get(configuration);
} else if (filePath.startsWith("file://")) {
fileSystem = FileSystem.getLocal(configuration).getRawFileSystem();
}
从这里我使用 FileSystem 的 API 来读取文件。
请告诉我是否有比这更好的方法?
最佳答案
这有意义吗,
public static void main(String[] args) throws IOException {
Configuration conf = new Configuration();
conf.addResource(new Path("/hadoop/projects/hadoop-1.0.4/conf/core-site.xml"));
conf.addResource(new Path("/hadoop/projects/hadoop-1.0.4/conf/hdfs-site.xml"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the file path...");
String filePath = br.readLine();
Path path = new Path(filePath);
FileSystem fs = path.getFileSystem(conf);
FSDataInputStream inputStream = fs.open(path);
System.out.println(inputStream.available());
fs.close();
}
如果你走这条路,你不必检查。直接从 Path 获取 FileSystem,然后随心所欲。
关于java - 用 Java 读取 HDFS 和本地文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17072543/