用URL操作HDFS的时候,编写难度比较大,现在我们用hadoop提供的API来操作,会更方便,不说废话贴代码。
package com.hsl.test; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IOUtils; import org.junit.Test; /** * 利用FileSystem API来操作HDFS * @author <a href="mailto:[email protected]">huoshengliang</a> * */ public class FSTest { // hdfs主机路径 static final String PATH = "hdfs://master.dragon.org:9000"; /** * 得到文件系统 * @return * @throws IOException */ private FileSystem getFilSystem() throws IOException { Configuration configuration = new Configuration(); Path path = new Path(PATH); return path.getFileSystem(configuration); } /** * 创建文件 * @throws Exception */ @Test public void createFile() throws Exception { // 创建文件 createFileToHDFS(); } private FSDataOutputStream createFileToHDFS() throws IOException { FileSystem fileSystem = getFilSystem(); // 创建文件 return fileSystem.create(new Path("/wc/test.txt"), true); } /** * 写入文件 * @throws Exception */ @Test public void writeFile() throws Exception { // 创建文件 FSDataOutputStream outputStream = createFileToHDFS(); // 写入指定内容到文件中 outputStream.writeBytes("hello hadoop"); outputStream.close(); } /** * 读取文件到控制台 * @throws Exception */ @Test public void readFile() throws Exception { FileSystem fileSystem = getFilSystem(); FSDataInputStream inputStream = fileSystem.open(new Path("/wc/test.txt")); IOUtils.copyBytes(inputStream, System.out, 1024, true); } /** * 删除文件 * @throws Exception */ @Test public void delFile() throws Exception { FileSystem fileSystem = getFilSystem(); fileSystem.deleteOnExit(new Path("/wc/test.txt")); } }
以上代码的前提是已经配置好hadoop,并用eclipse连接没问题的情况下运行的,在新建工程后,把hadoop中的一些jar包导入到工程中
下面来说明几点
Hadoop文件系统
基本的文件系统命令操作, 通过hadoop fs -help可以获取所有的命令的详细帮助文件。
Java抽象类org.apache.hadoop.fs.FileSystem定义了hadoop的一个文件系统接口。该类是一个抽象类,通过以下两种静态工厂方法可以过去FileSystem实例:
public static FileSystem.get(Configuration conf) throws IOException
public static FileSystem.get(URI uri, Configuration conf) throws IOException
具体方法实现:
1、public boolean mkdirs(Path f) throws IOException
一次性新建所有目录(包括父目录), f是完整的目录路径。
2、public FSOutputStream create(Path f) throws IOException
创建指定path对象的一个文件,返回一个用于写入数据的输出流
create()有多个重载版本,允许我们指定是否强制覆盖已有的文件、文件备份数量、写入文件缓冲区大小、文件块大小以及文件权限。
3、public boolean copyFromLocal(Path src, Path dst) throws IOException
将本地文件拷贝到文件系统
4、public boolean exists(Path f) throws IOException
检查文件或目录是否存在
5、public boolean delete(Path f, Boolean recursive)
永久性删除指定的文件或目录,如果f是一个空目录或者文件,那么recursive的值就会被忽略。只有recursive=true时,一个非空目录及其内容才会被删除。
6、FileStatus类封装了文件系统中文件和目录的元数据,包括文件长度、块大小、备份、修改时间、所有者以及权限信息。
通过"FileStatus.getPath()"可查看指定HDFS中某个目录下所有文件。