DFS文件读写
在使用hadoop集群时,经常会要用到一个全局性的文件,或是一个hash文件或是一个词表等等。HadoopDfsReadWriteExample
其实在DFS文件系统中读写文件与其它文件系统本质上是一样的。以下的这个例子就是从一个DFS中读出再写入到另一个DFS中。
HadoopFileSystem API这个类就是用来做这个读写用的。
首选要用一个配置对象来产生一个 FileSystem 的对象。
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
Path inFile = new Path(argv);
Path outFile = new Path(argv);
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
Path inFile = new Path(argv);
Path outFile = new Path(argv);
先检验一下if (!fs.exists(inFile)) printAndExit("Input file not found"); if (!fs.isFile(inFile)) printAndExit("Input should be a file"); if (fs.exists(outFile)) printAndExit("Output already exists");if (!fs.exists(inFile))
printAndExit("Input file not found");
if (!fs.isFile(inFile))
printAndExit("Input should be a file");
if (fs.exists(outFile))
printAndExit("Output already exists");
首先是打开一个文件流:FSDataInputStream in = fs.open(inFile);再打开一个输出的文件流:FSDataOutputStream out = fs.create(outFile);从输入流中读入并输出到输出到流中while ((bytesRead = in.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); }while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
再把两个流都关闭in.close(); out.close();
页:
[1]