hadoop分布式文件系统(HDFS)常用API学习

1、org.apache.hadoop.fs.FileSystem

范围 方法 返回值 描述
addDelegationTokens(String renewer, Credentials credentials) Token<?>[] 添加新的token,返回所有的token
append(Path f) FSDataOutputStream 添加一个已经存在的文件
append(Path f, int bufferSize) FSDataOutputStream 添加一个已经存在的文件,自定义缓冲区
abstract append(Path f, int bufferSize, Progressable progress) FSDataOutputStream 添加一个已经存在的文件,自定义缓冲区和写入过程
appendFile(Path path) FSDataOutputStreamBuilder 创建一个FSDataOutputStreamBuilder,用于添加文件
static areSymlinksEnabled() boolean 文件系统中的符号连接是否可用
cancelDeleteOnExit(Path f) boolean 在FileSystem关闭时取消删除指定的文件
protected canonicalizeUri(URI uri) URI 规范给定的URI
protected checkPath(Path path) void 检查Path是否属于此FileSystem。
static clearStatistics() void 重置所有文件系统的所有统计信息
close() void 关闭这个FileSystem实例
static closeAll() void 关闭所有缓存的FileSystem实例
static closeAllForUGI(UserGroupInformation ugi) void 关闭给定UGI的所有缓存文件系统实例
completeLocalOutput(Path fsOutputFile, Path tmpLocalFile) void 当我们都写完目标时调用。
concat(Path trg, Path[] psrcs) void 将存在的文件连接
copyFromLocalFile(boolean delSrc, boolean overwrite, Path[] srcs, Path dst) void 将本地文件复制到hdfs中
copyFromLocalFile(boolean delSrc, boolean overwrite, Path src, Path dst) void 将本地文件复制到hdfs中
copyFromLocalFile(boolean delSrc, Path src, Path dst) void 将本地文件复制到hdfs中
copyFromLocalFile(Path src, Path dst) void 将本地文件复制到hdfs中
copyToLocalFile(boolean delSrc, Path src, Path dst) void 将hdfs的文件复制到本地文件
copyToLocalFile(boolean delSrc, Path src, Path dst, boolean useRawLocalFileSystem) void 将hdfs的文件复制到本地文件
copyToLocalFile(Path src, Path dst) void 将hdfs的文件复制到本地文件
static create(FileSystem fs, Path file, FsPermission permission) FSDataOutputStream 创建一个文件,并添加权限(注意:并不能直接创建一个文件,而是创建了一个输入流,其他的也一样)
create(Path f) FSDataOutputStream 在指定的路径上创建一个FSDataOutputStream。
create(Path f, boolean overwrite) FSDataOutputStream 在指定的路径上创建一个FSDataOutputStream。
create(Path f, boolean overwrite, int bufferSize) FSDataOutputStream 在指定的路径上创建一个文件
create(Path f, boolean overwrite, int bufferSize, Progressable progress) FSDataOutputStream 在指定的路径上创建一个文件,自定义进度
create(Path f, boolean overwrite, int bufferSize, short replication, long blockSize) FSDataOutputStream 在指定的路径上创建一个文件
create(Path f, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) FSDataOutputStream 在指定的路径上创建一个文件
abstract create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) FSDataOutputStream 在指定的路径上创建一个文件
create(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress) FSDataOutputStream 在指定的路径上创建一个文件
create(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress, Options.ChecksumOpt checksumOpt) FSDataOutputStream 在指定的路径上创建一个文件
create(Path f, Progressable progress) FSDataOutputStream 在指定的路径上创建一个文件
create(Path f, short replication) FSDataOutputStream 在指定的路径上创建一个文件
create(Path f, short replication, Progressable progress) FSDataOutputStream 在指定的路径上创建一个文件
createFile(Path path) FSDataOutputStreamBuilder 创建一个FSDataOutputStreamBuilder,用于创建文件
createNewFile(Path f) boolean 创建一个空文件
createNonRecursive(Path f, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) FSDataOutputStream 在指定的路径中打开一个文件
createNonRecursive(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) FSDataOutputStream 在指定的路径中打开一个文件
createNonRecursive(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress) FSDataOutputStream 在指定的路径中打开文件
createSnapshot(Path path) Path 使用默认名称创建快照。
createSnapshot(Path path, String snapshotName) Path 创建一个快照
createSymlink(Path target, Path link, boolean createParent) void 创建一个符号连接
delete(Path f) boolean 删除一个文件
abstract delete(Path f, boolean recursive) boolean 是否循环删除一个文件及其子文件
deleteOnExit(Path f) boolean 当FileSystem关闭时,删除指定的文件
deleteSnapshot(Path path, String snapshotName) void 删除目录的快照
static enableSymlinks() void 启用符号连接
exists(Path f) boolean 检查路径是否存在
protected fixRelativePart(Path p) Path 修复相对路径
static get(Configuration conf) FileSystem 返回配置的FileSystem实例
static get(URI uri, Configuration conf) FileSystem 通过uri和配置文件实例一个FileSystem
static get(URI uri, Configuration conf, String user) FileSystem 获取基于uri,传入配置和用户的FileSystem实例
getAclStatus(Path path) AclStatus 获取文件或目录的ACL
static getAllStatistics() List<FileSystem.Statistics> 获取FileSystem中所有的统计信息
Collection<? getAllStoragePolicies() extends 检索此文件系统支持的所有存储策略
getBlockSize(Path f) long 获取FileSystem中块的大小
getCanonicalServiceName() String 获取此FileSystem的规范服务名称
protected getCanonicalUri() URI 返回此FileSystem的URI的规范化形式
getContentSummary(Path f) ContentSummary 返回给定的路径或文件的摘要信息
getDefaultBlockSize() long 获取FileSystem的默认块大小
getDefaultBlockSize(Path f) long 返回大型输入文件应该被最优分割的字节数,以最大限度地减少I/O时间
protected getDefaultPort() int 获取此FileSystem的默认端口
getDefaultReplication() short 获取此FileSystem的默认副本数
getDefaultReplication(Path path) short 获取路径的默认复本数
static getDefaultUri(Configuration conf) URI 从配置获取默认的FileSystem URI
getFileBlockLocations(FileStatus file, long start, long len) BlockLocation[] 返回包含给定文件部分的主机名,偏移量和大小的数组
getFileBlockLocations(Path p, long start, long len) BlockLocation[] 返回包含给定文件部分的主机名,偏移量和大小的数组
getFileChecksum(Path f) FileChecksum 如果FS支持校验和,则获取文件的校验和
getFileChecksum(Path f, long length) FileChecksum 获取从文件开始到特定长度获取文件的校验和
getFileLinkStatus(Path f) FileStatus 返回表示路径的文件状态对象,如果路径指向符号链接,则返回符号链接的FileStatus。如果底层文件系统不支持符号链接,则该行为等同于#getFileStatus()
abstract getFileStatus(Path f) FileStatus 返回表示路径的文件状态对象。
static getFileSystemClass(String scheme, Configuration conf) Class<?> 获取文件系统的FileSystem实现类。
protected getFSofPath(Path absOrFqPath, Configuration conf) static 通过path和配置获取FileSystem实例
static getGlobalStorageStatistics() GlobalStorageStatistics 获取全局存储统计信息
getHomeDirectory() Path 在此FileSystem中返回当前用户的主目录。
protected getInitialWorkingDirectory() Path 注意:使用新的FileContext类,getWorkingDirectory()将被删除
getLength(Path f) long 获取文件内容的长度
getLinkTarget(Path f) Path 获取符号连接的实际文件
static getLocal(Configuration conf) LocalFileSystem 获取本地文件系统
getName() String 获取文件系统的名称
static getNamed(String name, Configuration conf) FileSystem 根据名字和配置实例一个FileSystem
getPathHandle(FileStatus stat, Options.HandleOpt… opt) PathHandle 创建一个持久的,可序列化的给定实体对象的处理
getQuotaUsage(Path f) QuotaUsage 返回给定文件的配额使用情况
getReplication(Path src) short 获取指定文件得到副本数量
getScheme() String 返回此FileSystem的Scheme
getServerDefaults() FsServerDefaults 返回FileSystem的默认Server
getServerDefaults(Path p) FsServerDefaults 返回一组Server的默认配置值
static getStatistics() Map<String,FileSystem.Statistics> 获取FileSystem中的统计数据
static getStatistics(String scheme, Class<? extends FileSystem> cls) FileSystem.Statistics
getStatus() FsStatus 返回描述文件系统使用和容量的状态对象。
getStatus(Path p) FsStatus 返回描述文件系统使用和容量的状态对象。
getStoragePolicy(Path src) BlockStoragePolicySpi 查询给定文件或目录的有效存储策略ID
getStorageStatistics() StorageStatistics 获取此FileSystem对象的存储情况
getTrashRoot(Path path) Path 当指定的路径被删除时,获取当前用户的垃圾桶根目录
getTrashRoots(boolean allUsers) Collection<FileStatus> 获取当前用户或所有用户的所有垃圾桶
abstract getUri() URI 返回标识此文件系统的URI
getUsed() long 返回文件系统中所有文件的总大小
getUsed(Path path) long 返回指定路径中所有文件的总大小
abstract getWorkingDirectory() Path 获取给定文件系统的当前工作目录
getXAttr(Path path, String name) byte[] 获取文件或目录的xattr key和value
getXAttrs(Path path) Map<String,byte[]> 获取文件或目录的所有xattr key/value对
getXAttrs(Path path, List<String> names) Map<String,byte[]> 获取文件或目录的所有xattrs
globStatus(Path pathPattern) FileStatus[] 返回所有匹配filePattern的FileStatus,但是不去校验文件
globStatus(Path pathPattern, PathFilter filter) FileStatus[] 返回所有符合pathPattern,并且过滤后的FileStatus
initialize(URI name, Configuration conf) void 初始化文件系统
isDirectory(Path f) boolean 判断一个文件是不是文件件
isFile(Path f) boolean 判断path对象是不是一个文件
listCorruptFileBlocks(Path path) RemoteIterator<Path> 列出损坏的文件块
listFiles(Path f, boolean recursive) RemoteIterator<LocatedFileStatus> 列出给定路径中文件的状态和块位置
listLocatedStatus(Path f) RemoteIterator<LocatedFileStatus> 如果路径是目录,则列出给定路径中文件/目录的状态
protected listLocatedStatus(Path f, PathFilter filter) RemoteIterator<LocatedFileStatus> 列出一个目录
abstract listStatus(Path f) FileStatus[] 如果路径是目录,则列出给定路径中文件/目录的状态
listStatus(Path[] files) FileStatus[] 使用默认路径过滤器过滤给定路径列表中的文件/目录
listStatus(Path[] files, PathFilter filter) FileStatus[] 使用用户提供的路径过滤器过滤给定路径列表中的文件/目录
listStatus(Path f, PathFilter filter) FileStatus[] 使用用户提供的路径过滤器过滤给定路径中的文件/目录
listStatusIterator(Path p) RemoteIterator<FileStatus> 返回一个远程迭代器,以便在使用条目时按需调用后续调用
listXAttrs(Path path) List<String> 获取文件或目录的所有xattr名称
makeQualified(Path path) Path 限定使用此FileSystem的路径,如果相对,则返回绝对路径
static mkdirs(FileSystem fs, Path dir, FsPermission permission) boolean 使用用提供的权限创建一个目录。
mkdirs(Path f) boolean 以默认权限创建一个目录
abstract mkdirs(Path f, FsPermission permission) boolean 创建指定权限的文件,如果文件父目录不存在,则会自动创建
modifyAclEntries(Path path, List<AclEntry> aclSpec) void 修改文件和目录的ACL条目
moveFromLocalFile(Path[] srcs, Path dst) void 将本地文件移动到FileSystem
moveFromLocalFile(Path src, Path dst) void 将本地文件移动到FileSystem
moveToLocalFile(Path src, Path dst) void 将文件复制到本地文件系统,然后将其从远程文件系统中删除(如果已成功复制)
static newInstance(Configuration conf) FileSystem 为所提供的配置的默认文件系统返回一个唯一配置的FileSystem实现。
static newInstance(URI uri, Configuration config) FileSystem 返回此URI的模式和权限的FileSystem
static newInstance(URI uri, Configuration conf, String user) FileSystem 返回此URI的方案和权限以及给定用户的FileSystem
static newInstanceLocal(Configuration conf) LocalFileSystem 获取唯一的本地FileSystem对象
open(Path f) FSDataInputStream 在指定的路径中打开一个FSDataInputStream
open(PathHandle fd) FSDataInputStream 打开一个匹配PathHandle实例的FSDataInputStream
open(PathHandle fd, int bufferSize) FSDataInputStream 打开一个匹配PathHandle实例的FSDataInputStream
abstract open(Path f, int bufferSize) FSDataInputStream 在指定的路径中打开一个FSDataInputStream
static printStatistics() void 将所有统计信息以流Sysem.out输处
protected processDeleteOnExit() void 删除标记为退出时删除的所有路径
removeAcl(Path path) void 删除除文件和目录的基本ACL条目以外的所有条目
removeAclEntries(Path path, List<AclEntry> aclSpec) void 从文件和目录中删除ACL条目
removeDefaultAcl(Path path) void 从文件和目录中删除所有默认ACL条目。
removeXAttr(Path path, String name) void 删除文件或目录的xattr。
abstract rename(Path src, Path dst) boolean 将Path src重命名为Path dst
protected rename(Path src, Path dst, Options.Rename… options) void
renameSnapshot(Path path, String snapshotOldName, String snapshotNewName) void 重命名快照
protected resolveLink(Path f) Path 通过任何符号链接或挂载点解析路径,返回路径的全限定路径
resolvePath(Path p) Path 通过任何符号链接或挂载点解析路径,返回路径的全限定路径
setAcl(Path path, List<AclEntry> aclSpec) void 完全替代文件和目录的ACL,丢弃所有现有条目
static setDefaultUri(Configuration conf, String uri) void 在配置中设置默认的FileSystem URI
static setDefaultUri(Configuration conf, URI uri) void 在配置中设置默认的FileSystem URI
setOwner(Path p, String username, String groupname) void 设置一个路径的所有者
setPermission(Path p, FsPermission permission) void 设置路径的权限
setReplication(Path src, short replication) boolean 设置现有文件的复本数
setStoragePolicy(Path src, String policyName) void 设置给定文件或目录的存储策略
setTimes(Path p, long mtime, long atime) void 设置文件的访问时间
setVerifyChecksum(boolean verifyChecksum) void 设置验证校验和标志
abstract setWorkingDirectory(Path new_dir) void 设置给定文件系统的当前工作目录
setWriteChecksum(boolean writeChecksum) void 设置写校验和标志
setXAttr(Path path, String name, byte[] value) void 设置文件或目录的xattr。
setXAttr(Path path, String name, byte[] value, EnumSet<XAttrSetFlag> flag) void 设置文件或目录的xattr
startLocalOutput(Path fsOutputFile, Path tmpLocalFile) Path 返回用户可以将输出写入的本地文件
supportsSymlinks() boolean 是都支持符号连接
truncate(Path f, long newLength) boolean 将指定路径中的文件截断为指定的大小
unsetStoragePolicy(Path src) void 取消设置给定文件或目录的存储策略集

2、org.apache.hadoop.fs.Path

方法 返回值 说明 备注
new Path(String path) String 构造函数
new Path(URI url) boolean 构造函数
getName() String 获取文件或者文件夹的名字
path.isAbsolute() boolean 判断文件夹或文件是否是绝对路径
isRoot() boolean 是不是根目录
depth() int 文件或文件夹的深度 相对与根路径,根路径是0,用户目录是2,….
getParent() String 文件或文件夹的父路径 如果是根目录则返回null
isAbsoluteAndSchemeAuthorityNull boolean 如果文件或目录是绝对路径,并且Scheme和Authority都是null返回true
isUriPathAbsolute boolean 文件或目录的uri path 是不是绝对路径
suffix(String s) Path 为文件或目录添加后缀
toUri() URI path对象转uri对象

3、org.apache.hadoop.FileStatus

方法 返回值 说明 备注
getPath() Path 返回文件的Path对象
getAccessTime long 返回文件的上一次访问时间
getGroup() String 返回文件的组属性
getOwner() String 返回文件的拥有者
getBlockSize() long 返回文件的块大小
getLen() long 返回文件内容大小
getPermission() FsPermission 返回文件的权限对象
getModificationTime() long 返回文件最后修改时间
getSymlink() Path 返回文件符号连接路径
hasAcl() boolean 文件是否设置ACL
isEncrypted() boolean 文件是否加密
isFile() boolean 判断是否是文件
getReplication() int 返回文件副本数
isSnapshotEnabled() boolean 是否使用快照

单元测试

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.Cluster;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

public class FileStatusTest {
    private FileSystem fs;
    private Path path = new Path("hdfs://localhost/user/lhy/poem");
    private Cluster cluster;

    @Before
    public void setUp() throws IOException, InterruptedException {
        Configuration configuration = new Configuration();
        configuration.set("fs.defaultFS","hdfs://localhost");
        fs = FileSystem.get(configuration);
    }


    @After
    public void tearDown() throws IOException {
        if (fs != null){
            fs.close();
        }

        if (cluster != null){
            cluster.close();
        }
    }

    @Test
    public void pathTest() throws IOException {
        System.out.println("------------org.apache.hadoop.fs.Path-test-start----------");
        System.out.println("文件或目录的名字:"+ path.getName());
        System.out.println("文件或目录是否是绝对路径:" + path.isAbsolute());
        System.out.println("是不是根目录:" + path.isRoot());
        System.out.println("根目录的深度是1,用户目录深度是2,此处文件的深度是: " + path.depth());
        System.out.println("文件或目录的父文件夹:" + path.getParent());
        System.out.println("文件或目录isAbsoluteAndSchemeAuthorityNull:" + path.isAbsoluteAndSchemeAuthorityNull());
        System.out.println("文件或目录的父文件夹:" + path.getParent());
        System.out.println("文件或目录的URI Path 是不是绝对路径:" + path.isUriPathAbsolute());
        System.out.println("为文件或目录添加后缀:" + path.suffix(".TXT"));
        System.out.println("path对象转uri对象:" + path.toUri());
        System.out.println("------------org.apache.hadoop.fs.Path-test-end----------\n");
    }


    @Test
    public void fileStatusTest() throws IOException {
        System.out.println("------------org.apache.hadoop.fs.FileStatus-test-start----------");
        FileStatus fileStatus = fs.getFileStatus(path);
        System.out.println("文件的path:" + fileStatus.getPath());
        System.out.println("文件的上一次访问时间:" + fileStatus.getAccessTime());
        System.out.println("文件所属组:" + fileStatus.getGroup());
        System.out.println("文件的所属:" + fileStatus.getOwner());
        System.out.println("文件快的大小(单位bit):" + fileStatus.getBlockSize());
        System.out.println("文件内容长度" + fileStatus.getLen());
        System.out.println("文件的权限:"+ fileStatus.getPermission());
        System.out.println("最后修改时间:"+ fileStatus.getModificationTime());
//        System.out.println("文件连接的路径(软连接或者硬连接的路径):"+ fileStatus.getSymlink());//if link path not found,will be throw an exception
        System.out.println("是否是一个文件夹:"+fileStatus.isDirectory());
        System.out.println("文件是否设置ACL:"+fileStatus.hasAcl());
        System.out.println("文件是否加密:"+fileStatus.isEncrypted());
        System.out.println("是否是文件:"+fileStatus.isFile());
        System.out.println("文件个副本个数:"+fileStatus.getReplication());
        System.out.println("是否使用快照:"+fileStatus.isSnapshotEnabled());
        System.out.println("------------org.apache.hadoop.fs.FileStatus-test-end----------\n");
    }

    @Test
    public void filSystemTest() throws IOException {
        Path path = new Path("poem");

        System.out.println("目录或文件是否存在:" + fs.exists(path));
        System.out.println("获取文件系统的服务地址:" + fs.getCanonicalServiceName());
//        Path newPath = new Path("test");
//        System.out.println("用户目录下创建文件夹test:" + fs.mkdirs(newPath));//如果已经存在,则会创建失败,抛出异常

//        System.out.println("本地文件拷贝到hdfs,文件存在则会覆盖:");
//        Path localPath = new Path(URI.create("/Users/lhy/Desktop/春江花月夜.poem"));
//        fs.copyFromLocalFile(localPath,path);

        System.out.println("列出所有的文件:");
        FileStatus[] fileStatuses = fs.listStatus(path);
        for (FileStatus fileStatus : fileStatuses){
            System.out.println(fileStatus.getPath());
        }

        System.out.println("列出所有过滤后的文件:");
        FileStatus[] fileStatuses2 = fs.listStatus(path, path2 -> !path2.getName().contains("txt"));
        for (FileStatus fileStatus : fileStatuses2){
            System.out.println(fileStatus.getPath());
        }

    }

}

猜你喜欢

转载自blog.csdn.net/qq_36027670/article/details/79912206