【Android学习】File文件

1,概念

1)存储模式

①Context.MODE_PRIVATE

默认操作模式,代表该文件是私有数据,只能被本应用本身访问。
写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中,可以使用Context.MODE_APPEND。

②Context.MODE_APPEND

该模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。

③Context.MODE_WORLD_READABLE和_WRITEABLE

用来控制其他应用读写该文件的权限。
Context.MODE_WORLD_WRITEABLE:表示文件可以被其他应用写入。

④Context.MODE_READABLE

表示当前文件可以被其他应用读取。

⑤举例

希望文件可以被其他应用写入:

openFileOutput("itcast.txt",Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

2)权限

<!--在SD卡中创建于删除文件权限-->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!--在SD卡中写入数据权限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2,IO

手机存储器、SD卡内文件的读写

1)断点续传和断点下载

都是用的RandomAccessFile, 它具有移动指定的文件大小的位置的功能seek 。

断点续传是由服务器给客户端一个已经上传的位置标记position,然后客户端再将文件指针移动到相应的position,通过输入流将文件剩余部分读出来传输给服务器。

断点下载 是由客户端告诉服务器已经下载的大小,然后服务器会将指针移动到相应的position,继续读出,把文件返回给客户端。 当然为了下载的更快一下,也可以多线程下载,那么基本实现就是给每个线程分配固定的字节的文件,分别去读。

3,基本操作

1)SD卡

①判断手机是否插入了SD卡

Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)

②获取SD卡目录:

File sdDir = Environment.getExternalStorageDirectory();

③使用IO流读写SD卡上的文件:

deleteFile("auto.txt");//删除指定的文件

String f[] = fileList();//查看目录下的所有文件

File file = getDir("mydir",Context.MODE_PRIVATE);//创建子目录

String path = file.getCanonicalPath();//获取绝对路径

2)创建

①判断文件夹是否存在,不存在则创建

 static boolean isFolderExists(String strFolder) {
        File file = new File(strFolder);
        if (!file.exists()) {
            if (file.mkdirs()) {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }

3)删除

①删除文件夹及文件夹中的内容

public static boolean delFolder(String dir) {
        // 如果dir不以文件分隔符结尾,自动添加文件分隔符
        if (!dir.endsWith(File.separator))
            dir = dir + File.separator;
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在,或者不是一个目录,则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            System.out.println("删除目录失败:" + dir + "不存在!");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
            // 删除子目录
            else if (files[i].isDirectory()) {
                flag = delFolder(files[i]
                        .getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            System.out.println("删除目录失败!");
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
            System.out.println("删除目录" + dir + "成功!");
            return true;
        } else {
            return false;
        }
    }

②删除单个文件

 /**
     * 删除单个文件
     *
     * @param fileName 要删除的文件的文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    private static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功!");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败!");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败:" + fileName + "不存在!");
            return false;
        }
    }

3)文件打开

①通过其它软件打开文件

 public void openFile(String filePath) {

        File file = new File(filePath);
        if (file.exists()) {
            Uri path = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(path, FileUtil.getFileType(filePath.substring(filePath.lastIndexOf("."), filePath.length())));
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(intent);
        }else{
            basalView.showToastShort("文件不存在或已被删除");
        }
    }

②根据后缀名查看intent类型

/**
     * @param suffix 后缀 如:  txt
     * @return
     */
    public static String getFileType(String suffix) {

        switch (suffix) {
//            case "evy":
//                return "application/envoy";
//            case "fif":
//                return "application/fractals";
//            case "spl":
//                return "application/futuresplash";
//            case "hta":
//                return "application/hta";
//            case "acx":
//                return "application/internet-property-stream";
//            case "hqx":
//                return "application/mac-binhex40";
            case "doc":
            case "dot":
                return "application/msword";
//            case "*":
//            case "bin":
//            case "class":
//            case "dms":
//            case "exe":
//            case "lha":
//            case "lzh":
//                return "application/octet-stream";
//            case "oda":
//                return "application/oda";
//            case "axs":
//                return "application/olescript";
            case "pdf":
                return "application/pdf";
//            case "prf":
//                return "application/pics-rules";
//            case "p10":
//                return "application/pkcs10";
//            case "crl":
//                return "application/pkix-crl";
//            case "ai":
//            case "eps":
//            case "ps":
//                return "application/postscript";
//            case "rtf":
//                return "application/rtf";
//            case "setpay":
//                return "application/set-payment-initiation";
//            case "setreg":
//                return "application/set-registration-initiation";
            case "xla":
            case "xlc":
            case "xlm":
            case "xls":
            case "xlt":
            case "xlw":
                return "application/vnd.ms-excel";
//            case "msg":
//                return "application/vnd.ms-outlook";
//            case "sst":
//                return "application/vnd.ms-pkicertstore";
//            case "cat":
//                return "application/vnd.ms-pkiseccat";
//            case "stl":
//                return "application/vnd.ms-pkistl";
//            case "pot":
//            case "pps":
//            case "ppt":
//                return "application/vnd.ms-powerpoint";
            case "mpp":
                return "application/vnd.ms-project";
//            case "wcm":
//            case "wdb":
//            case "wks":
//            case "wps":
//                return "application/vnd.ms-works";
//            case "hlp":
//                return "application/winhlp";
//            case "bcpio":
//                return "application/x-bcpio";
//            case "cdf":
//                return "application/x-cdf";
//            case "z":
//                return "application/x-compress";
//            case "tgz":
//                return "application/x-compressed";
//            case "cpio":
//                return "application/x-cpio";
//            case "csh":
//                return "application/x-csh";
//            case "dcr":
//            case "dir":
//            case "dxr":
//                return "application/x-director";
//            case "dvi":
//                return "application/x-dvi";
//            case "gtar":
//                return "application/x-gtar";
//            case "gz":
//                return "application/x-gzip";
//            case "hdf":
//                return "application/x-hdf";
//            case "ins":
//            case "isp":
//                return "application/x-internet-signup";
//            case "iii":
//                return "application/x-iphone";
//            case "js":
//                return "application/x-javascript";
//            case "latex":
//                return "application/x-latex";
//            case "mdb":
//                return "application/x-msaccess";
//            case "crd":
//                return "application/x-mscardfile";
//            case "clp":
//                return "application/x-msclip";
//            case "dll":
//                return "application/x-msdownload";
//            case "m13":
//            case "m14":
//            case "mvb":
//                return "application/x-msmediaview";
//            case "wmf":
//                return "application/x-msmetafile";
//            case "mny":
//                return "application/x-msmoney";
//            case "pub":
//                return "application/x-mspublisher";
//            case "scd":
//                return "application/x-msschedule";
//            case "trm":
//                return "application/x-msterminal";
//            case "wri":
//                return "application/x-mswrite";
//            case "nc":
//                return "application/x-netcdf";
//            case "pma":
//            case "pmc":
//            case "pml":
//            case "pmr":
//            case "pmw":
//                return "application/x-perfmon";
//            case "p12":
//            case "pfx":
//                return "application/x-pkcs12";
//            case "p7b":
//            case "spc":
//                return "application/x-pkcs7-certificates";
//            case "p7r":
//                return "application/x-pkcs7-certreqresp";
//            case "p7c":
//            case "p7m":
//                return "application/x-pkcs7-mime";
//            case "p7s":
//                return "application/x-pkcs7-signature";
//            case "sh":
//                return "application/x-sh";
//            case "shar":
//                return "application/x-shar";
//            case "swf":
//                return "application/x-shockwave-flash";
//            case "sit":
//                return "application/x-stuffit";
//            case "sv4cpio":
//                return "application/x-sv4cpio";
//            case "sv4crc":
//                return "application/x-sv4crc";
//            case "tar":
//                return "application/x-tar";
//            case "tcl":
//                return "application/x-tcl";
//            case "tex":
//                return "application/x-tex";
//            case "texi":
//                return "application/x-texinfo";
//            case "texinfo":
//                return "application/x-texinfo";
//            case "roff":
//            case "t":
//            case "tr":
//                return "application/x-troff";
//            case "man":
//                return "application/x-troff-man";
//            case "me":
//                return "application/x-troff-me";
//            case "ms":
//                return "application/x-troff-ms";
//            case "ustar":
//                return "application/x-ustar";
//            case "src":
//                return "application/x-wais-source";
//            case "cer":
//            case "crt":
//            case "der":
//                return "application/x-x509-ca-cert";
//            case "pko":
//                return "application/ynd.ms-pkipko";
//            case "zip":
//                return "application/zip";
//            case "au":
//            case "snd":
//                return "audio/basic";
//            case "mid":
//            case "rmi":
//                return "audio/mid";
//            case "mp3":
//                return "audio/mpeg";
//            case "aif":
//            case "aifc":
//            case "aiff":
//                return "audio/x-aiff";
//            case "m3u":
//                return "audio/x-mpegurl";
//            case "ra":
//            case "ram":
//                return "audio/x-pn-realaudio";
//            case "wav":
//                return "audio/x-wav";
//            case "bmp":
//                return "image/bmp";
//            case "cod":
//                return "image/cis-cod";
//            case "gif":
//                return "image/gif";
//            case "ief":
//                return "image/ief";
            case "jpe":
            case "jpeg":
            case "jpg":
                return "image/jpeg";
//            case "jfif":
//                return "image/pipeg";
//            case "svg":
//                return "image/svg+xml";
//            case "tif":
//            case "tiff":
//                return "image/tiff";
//            case "ras":
//                return "image/x-cmu-raster";
//            case "cmx":
//                return "image/x-cmx";
//            case "ico":
//                return "image/x-icon";
//            case "pnm":
//                return "image/x-portable-anymap";
//            case "pbm":
//                return "image/x-portable-bitmap";
//            case "pgm":
//                return "image/x-portable-graymap";
//            case "ppm":
//                return "image/x-portable-pixmap";
//            case "rgb":
//                return "image/x-rgb";
//            case "xpm":
//            case "xbm":
//                return "image/x-xbitmap";
//            case "xwd":
//                return "image/x-xwindowdump";
//            case "mht":
//            case "mhtml":
//            case "nws":
//                return "message/rfc822";
//            case "css":
//                return "text/css";
//            case "323":
//                return "text/h323";
//            case "htm":
//            case "html":
//            case "stm":
//                return "text/html";
//            case "uls":
//                return "text/iuls";
//            case "bas":
//            case "c":
//            case "h":
            case "txt":
                return "text/plain";
//            case "rtx":
//                return "text/richtext";
//            case "sct":
//                return "text/scriptlet";
//            case "tsv":
//                return "text/tab-separated-values";
//            case "htt":
//                return "text/webviewhtml";
//            case "htc":
//                return "text/x-component";
//            case "etx":
//                return "text/x-setext";
//            case "vcf":
//                return "text/x-vcard";
//            case "mp2":
//            case "mpa":
//            case "mpe":
//            case "mpeg":
//            case "mpg":
//            case "mpv2":
//                return "video/mpeg";
//            case "mov":
//                return "video/quicktime";
//            case "qt":
//                return "video/quicktime";
//            case "lsf":
//                return "video/x-la-asf";
//            case "lsx":
//            case "asf":
//            case "asr":
//            case "asx":
//                return "video/x-la-asf";
//            case "avi":
//                return "video/x-msvideo";
//            case "movie":
//                return "video/x-sgi-movie";
//            case "flr":
//            case "vrml":
//            case "wrl":
//            case "wrz":
//            case "xaf":
//            case "xof":
//                return "x-world/x-vrml";
        }
        return "text/plain";
    }

4)获取文件大小

file.length() //单位为KB
 /**
     * 格式化单位
     *
     * @param size
     */
    public  String getFormatSize(double size) {
        double kiloByte = size / 1024;
        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }

5)zip的压缩和解压

用过java做压缩或解压的都知道,jdk提供的zip只能按UTF-8格式处理,所有jdk提供的zip不能支持中文文件名,可以采用Apache的zip包解决中文文件名问题。
下载地址:apache-ant-zip.jar

package cn.tzz.zip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

/**
 * ZIP工具包(支持中文)
 * 依赖:ant-1.9.6.jar
 */
public class CHZipUtils {

    /**使用GBK编码可以避免压缩中文文件名乱码*/
    private static final String CHINESE_CHARSET = "GBK";
    /**文件读取缓冲区大小*/
    private static final int CACHE_SIZE = 1024;

    /**
     * 压缩文件
     * @param sourceFolder 压缩文件夹
     * @param zipFilePath 压缩文件输出路径
     */
    public static void zip(String sourceFolder, String zipFilePath) {
        OutputStream os = null;
        BufferedOutputStream bos = null;
        ZipOutputStream zos = null;
        try {
            os = new FileOutputStream(zipFilePath);
            bos = new BufferedOutputStream(os);
            zos = new ZipOutputStream(bos);
            // 解决中文文件名乱码
            zos.setEncoding(CHINESE_CHARSET);
            File file = new File(sourceFolder);
            String basePath = null;
            if (file.isDirectory()) {//压缩文件夹
                basePath = file.getPath();
            } else {
                basePath = file.getParent();
            }
            zipFile(file, basePath, zos);

        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            try {
                if (zos != null) {
                    zos.closeEntry();
                    zos.close();
                }
                if (bos != null) {
                    bos.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 递归压缩文件
     * @param parentFile
     * @param basePath
     * @param zos
     * @throws Exception
     */
    private static void zipFile(File parentFile, String basePath, ZipOutputStream zos) throws Exception {
        File[] files = new File[0];
        if (parentFile.isDirectory()) {
            files = parentFile.listFiles();
        } else {
            files = new File[1];
            files[0] = parentFile;
        }
        String pathName;
        InputStream is;
        BufferedInputStream bis;
        byte[] cache = new byte[CACHE_SIZE];
        for (File file : files) {
            if (file.isDirectory()) {
                pathName = file.getPath().substring(basePath.length() + 1) + File.separator;
                zos.putNextEntry(new ZipEntry(pathName));
                zipFile(file, basePath, zos);
            } else {
                pathName = file.getPath().substring(basePath.length() + 1);
                is = new FileInputStream(file);
                bis = new BufferedInputStream(is);
                zos.putNextEntry(new ZipEntry(pathName));
                int nRead = 0;
                while ((nRead = bis.read(cache, 0, CACHE_SIZE)) != -1) {
                    zos.write(cache, 0, nRead);
                }
                bis.close();
                is.close();
            }
        }
    }

    /**
     * 解压压缩包
     * @param zipFilePath 压缩文件路径
     * @param destDir 解压目录
     */
    public static void unZip(String zipFilePath, String destDir) {
        ZipFile zipFile = null;
        try {
            BufferedInputStream bis = null;
            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            zipFile = new ZipFile(zipFilePath, CHINESE_CHARSET);
            Enumeration<ZipEntry> zipEntries = zipFile.getEntries();
            File file, parentFile;
            ZipEntry entry;
            byte[] cache = new byte[CACHE_SIZE];
            while (zipEntries.hasMoreElements()) {
                entry = (ZipEntry) zipEntries.nextElement();
                if (entry.isDirectory()) {
                    new File(destDir + entry.getName()).mkdirs();
                    continue;
                }
                bis = new BufferedInputStream(zipFile.getInputStream(entry));
                file = new File(destDir + entry.getName());
                parentFile = file.getParentFile();
                if (parentFile != null && (!parentFile.exists())) {
                    parentFile.mkdirs();
                }
                fos = new FileOutputStream(file);
                bos = new BufferedOutputStream(fos, CACHE_SIZE);
                int readIndex = 0;
                while ((readIndex = bis.read(cache, 0, CACHE_SIZE)) != -1) {
                    fos.write(cache, 0, readIndex);
                }
                bos.flush();
                bos.close();
                fos.close();
                bis.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                zipFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
//      String sourceFolder = "D:/test/1.txt";
//      String sourceFolder = "D:/test/中文名.txt";
        String sourceFolder = "D:/test/cms";
        String zipFilePath = "D:/test/zip/压缩文件.zip";
        String destDir = "D:/test/zip/";
        CHZipUtils.zip(sourceFolder, zipFilePath);
//      CHZipUtils.unZip(zipFilePath, destDir);
        System.out.println("********执行成功**********");
    }

}

4,demo

1)递归遍历文件目录结构,打印所有的目录名和文件名

public class FileDemo {
    public static void getFileListame(String strPath) {

        File dir = new File(strPath);
        File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
        if (files != null) {
            for (int i = 0; i < files.length; i++) {

                System.out.println(files[i].getName());

                if (files[i].isDirectory()) { // 判断是文件还是文件夹
                    getFileListame(files[i].getAbsolutePath()); // 获取文件绝对路径
                    System.out.println(files[i].getAbsolutePath() + files[i].getName());

                }

            }

        }

    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值