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添加一个已经存在的文件,自定义缓冲区
abstractappend(Path f, int bufferSize, Progressable progress)FSDataOutputStream添加一个已经存在的文件,自定义缓冲区和写入过程
appendFile(Path path)FSDataOutputStreamBuilder创建一个FSDataOutputStreamBuilder,用于添加文件
staticareSymlinksEnabled()boolean文件系统中的符号连接是否可用
cancelDeleteOnExit(Path f)boolean在FileSystem关闭时取消删除指定的文件
protectedcanonicalizeUri(URI uri)URI规范给定的URI
protectedcheckPath(Path path)void检查Path是否属于此FileSystem。
staticclearStatistics()void重置所有文件系统的所有统计信息
close()void关闭这个FileSystem实例
staticcloseAll()void关闭所有缓存的FileSystem实例
staticcloseAllForUGI(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的文件复制到本地文件
staticcreate(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在指定的路径上创建一个文件
abstractcreate(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删除一个文件
abstractdelete(Path f, boolean recursive)boolean是否循环删除一个文件及其子文件
deleteOnExit(Path f)boolean当FileSystem关闭时,删除指定的文件
deleteSnapshot(Path path, String snapshotName)void删除目录的快照
staticenableSymlinks()void启用符号连接
exists(Path f)boolean检查路径是否存在
protectedfixRelativePart(Path p)Path修复相对路径
staticget(Configuration conf)FileSystem返回配置的FileSystem实例
staticget(URI uri, Configuration conf)FileSystem通过uri和配置文件实例一个FileSystem
staticget(URI uri, Configuration conf, String user)FileSystem获取基于uri,传入配置和用户的FileSystem实例
getAclStatus(Path path)AclStatus获取文件或目录的ACL
staticgetAllStatistics()List<FileSystem.Statistics>获取FileSystem中所有的统计信息
Collection<?getAllStoragePolicies()extends检索此文件系统支持的所有存储策略
getBlockSize(Path f)long获取FileSystem中块的大小
getCanonicalServiceName()String获取此FileSystem的规范服务名称
protectedgetCanonicalUri()URI返回此FileSystem的URI的规范化形式
getContentSummary(Path f)ContentSummary返回给定的路径或文件的摘要信息
getDefaultBlockSize()long获取FileSystem的默认块大小
getDefaultBlockSize(Path f)long返回大型输入文件应该被最优分割的字节数,以最大限度地减少I/O时间
protectedgetDefaultPort()int获取此FileSystem的默认端口
getDefaultReplication()short获取此FileSystem的默认副本数
getDefaultReplication(Path path)short获取路径的默认复本数
staticgetDefaultUri(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()
abstractgetFileStatus(Path f)FileStatus返回表示路径的文件状态对象。
staticgetFileSystemClass(String scheme, Configuration conf)Class<?>获取文件系统的FileSystem实现类。
protectedgetFSofPath(Path absOrFqPath, Configuration conf)static通过path和配置获取FileSystem实例
staticgetGlobalStorageStatistics()GlobalStorageStatistics获取全局存储统计信息
getHomeDirectory()Path在此FileSystem中返回当前用户的主目录。
protectedgetInitialWorkingDirectory()Path注意:使用新的FileContext类,getWorkingDirectory()将被删除
getLength(Path f)long获取文件内容的长度
getLinkTarget(Path f)Path获取符号连接的实际文件
staticgetLocal(Configuration conf)LocalFileSystem获取本地文件系统
getName()String获取文件系统的名称
staticgetNamed(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的默认配置值
staticgetStatistics()Map<String,FileSystem.Statistics>获取FileSystem中的统计数据
staticgetStatistics(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>获取当前用户或所有用户的所有垃圾桶
abstractgetUri()URI返回标识此文件系统的URI
getUsed()long返回文件系统中所有文件的总大小
getUsed(Path path)long返回指定路径中所有文件的总大小
abstractgetWorkingDirectory()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>如果路径是目录,则列出给定路径中文件/目录的状态
protectedlistLocatedStatus(Path f, PathFilter filter)RemoteIterator<LocatedFileStatus>列出一个目录
abstractlistStatus(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的路径,如果相对,则返回绝对路径
staticmkdirs(FileSystem fs, Path dir, FsPermission permission)boolean使用用提供的权限创建一个目录。
mkdirs(Path f)boolean以默认权限创建一个目录
abstractmkdirs(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将文件复制到本地文件系统,然后将其从远程文件系统中删除(如果已成功复制)
staticnewInstance(Configuration conf)FileSystem为所提供的配置的默认文件系统返回一个唯一配置的FileSystem实现。
staticnewInstance(URI uri, Configuration config)FileSystem返回此URI的模式和权限的FileSystem
staticnewInstance(URI uri, Configuration conf, String user)FileSystem返回此URI的方案和权限以及给定用户的FileSystem
staticnewInstanceLocal(Configuration conf)LocalFileSystem获取唯一的本地FileSystem对象
open(Path f)FSDataInputStream在指定的路径中打开一个FSDataInputStream
open(PathHandle fd)FSDataInputStream打开一个匹配PathHandle实例的FSDataInputStream
open(PathHandle fd, int bufferSize)FSDataInputStream打开一个匹配PathHandle实例的FSDataInputStream
abstractopen(Path f, int bufferSize)FSDataInputStream在指定的路径中打开一个FSDataInputStream
staticprintStatistics()void将所有统计信息以流Sysem.out输处
protectedprocessDeleteOnExit()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。
abstractrename(Path src, Path dst)boolean将Path src重命名为Path dst
protectedrename(Path src, Path dst, Options.Rename… options)void
renameSnapshot(Path path, String snapshotOldName, String snapshotNewName)void重命名快照
protectedresolveLink(Path f)Path通过任何符号链接或挂载点解析路径,返回路径的全限定路径
resolvePath(Path p)Path通过任何符号链接或挂载点解析路径,返回路径的全限定路径
setAcl(Path path, List<AclEntry> aclSpec)void完全替代文件和目录的ACL,丢弃所有现有条目
staticsetDefaultUri(Configuration conf, String uri)void在配置中设置默认的FileSystem URI
staticsetDefaultUri(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设置验证校验和标志
abstractsetWorkingDirectory(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
isAbsoluteAndSchemeAuthorityNullboolean如果文件或目录是绝对路径,并且Scheme和Authority都是null返回true
isUriPathAbsoluteboolean文件或目录的uri path 是不是绝对路径
suffix(String s)Path为文件或目录添加后缀
toUri()URIpath对象转uri对象

3、org.apache.hadoop.FileStatus

方法返回值说明备注
getPath()Path返回文件的Path对象
getAccessTimelong返回文件的上一次访问时间
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());
        }

    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值