Java File类总结和FileUtils类

文件存在和类型判断

  创建出File类的对象并不代表该路径下有此文件或目录。

  用public boolean exists()可以判断文件是否存在。

 

  File类的对象可以是目录或者文件。

  如果是目录,public boolean isDirectory()返回true;

  如果是文件(非目录则是文件),public boolean isFile()返回true;

  但是注意需要先判断文件是否存在,如果文件不存在,上面两个方法都返回false,即不存在的File类对象既不是文件也不是目录

 

创建文件

  public boolean createNewFile()会创建一个新的空文件,只有该文件不存在的时候会创建,如果文件已经存在的话则返回false。

创建文件夹

  public boolean mkdir()

  创建目录,成功返回true。只能创建一个文件夹,要求所有的父目录都存在,否则创建失败。

  public boolean mkdirs()

  创建目录,成功返回true,会创建所有不存在的父目录。(注意即便最后创建失败,但是也可能创建了一些中间目录)。

  上面两个方法如果要创建的目录已经存在,不再重新创建,都返回false,只有新建目录返回true。

 

目录操作

  列出目录中的文件有以下方法可选:

  String[] list()

  String[] list(FilenameFilter filter)

  返回文件名数组。

  File[] listFiles()

  File[] listFiles(FileFilter filter)

  File[] listFiles(FilenameFilter filter)

  返回File数组。

 

  参数是文件或者文件名过滤器。

 

  注意返回为空和返回为null的意义是不同的。

  若不包含(符合条件的)文件,返回为空。

  但是如果返回为null,则表明调用方法的File对象可能不是一个目录,或者发生了IO错误。

 

删除文件

  boolean delete()方法会删除文件,如果File对象是文件则直接删除,对于目录来说,如果是空目录则直接删除,非空目录则无法删除,返回false。

  如果要删除的文件不能被删除则会抛出IOException。

 

  注意:不论是创建文件、创建目录还是删除文件,只有在动作真正发生的时候会返回true。

 

FileUtils类

  在项目中写一些工具类包装通用操作是很有必要的,看了一下apache的FileUtils类,copy了一些方法出来:

复制代码
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mengdd.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * FileUtils copied from org.apache.commons.io.FileUtils
 */
public class FileUtils {
    /**
     * Construct a file from the set of name elements.
     *
     * @param directory
     *            the parent directory
     * @param names
     *            the name elements
     * @return the file
     */
    public static File getFile(File directory, String... names) {
        if (directory == null) {
            throw new NullPointerException(
                    "directorydirectory must not be null");
        }
        if (names == null) {
            throw new NullPointerException("names must not be null");
        }
        File file = directory;
        for (String name : names) {
            file = new File(file, name);
        }
        return file;
    }

    /**
     * Construct a file from the set of name elements.
     *
     * @param names
     *            the name elements
     * @return the file
     */
    public static File getFile(String... names) {
        if (names == null) {
            throw new NullPointerException("names must not be null");
        }
        File file = null;
        for (String name : names) {
            if (file == null) {
                file = new File(name);
            }
            else {
                file = new File(file, name);
            }
        }
        return file;
    }

    /**
     * Opens a {@link FileInputStream} for the specified file, providing better
     * error messages than simply calling <code>new FileInputStream(file)</code>
     * .
     * <p>
     * At the end of the method either the stream will be successfully opened,
     * or an exception will have been thrown.
     * <p>
     * An exception is thrown if the file does not exist. An exception is thrown
     * if the file object exists but is a directory. An exception is thrown if
     * the file exists but cannot be read.
     *
     * @param file
     *            the file to open for input, must not be {@code null}
     * @return a new {@link FileInputStream} for the specified file
     * @throws FileNotFoundException
     *             if the file does not exist
     * @throws IOException
     *             if the file object is a directory
     * @throws IOException
     *             if the file cannot be read
     */
    public static FileInputStream openInputStream(File file) throws IOException {
        if (file.exists()) {
            if (file.isDirectory()) {
                throw new IOException("File '" + file
                        + "' exists but is a directory");
            }
            if (file.canRead() == false) {
                throw new IOException("File '" + file + "' cannot be read");
            }
        }
        else {
            throw new FileNotFoundException("File '" + file
                    + "' does not exist");
        }
        return new FileInputStream(file);
    }

    /**
     * Opens a {@link FileOutputStream} for the specified file, checking and
     * creating the parent directory if it does not exist.
     * <p>
     * At the end of the method either the stream will be successfully opened,
     * or an exception will have been thrown.
     * <p>
     * The parent directory will be created if it does not exist. The file will
     * be created if it does not exist. An exception is thrown if the file
     * object exists but is a directory. An exception is thrown if the file
     * exists but cannot be written to. An exception is thrown if the parent
     * directory cannot be created.
     *
     * @param file
     *            the file to open for output, must not be {@code null}
     * @param append
     *            if {@code true}, then bytes will be added to the
     *            end of the file rather than overwriting
     * @return a new {@link FileOutputStream} for the specified file
     * @throws IOException
     *             if the file object is a directory
     * @throws IOException
     *             if the file cannot be written to
     * @throws IOException
     *             if a parent directory needs creating but that fails
     */
    public static FileOutputStream openOutputStream(File file, boolean append)
            throws IOException {
        if (file.exists()) {
            if (file.isDirectory()) {
                throw new IOException("File '" + file
                        + "' exists but is a directory");
            }
            if (file.canWrite() == false) {
                throw new IOException("File '" + file
                        + "' cannot be written to");
            }
        }
        else {
            File parent = file.getParentFile();
            if (parent != null) {
                if (!parent.mkdirs() && !parent.isDirectory()) {
                    throw new IOException("Directory '" + parent
                            + "' could not be created");
                }
            }
        }
        return new FileOutputStream(file, append);
    }

    public static FileOutputStream openOutputStream(File file)
            throws IOException {
        return openOutputStream(file, false);
    }

    /**
     * Cleans a directory without deleting it.
     *
     * @param directory
     *            directory to clean
     * @throws IOException
     *             in case cleaning is unsuccessful
     */
    public static void cleanDirectory(File directory) throws IOException {
        if (!directory.exists()) {
            String message = directory + " does not exist";
            throw new IllegalArgumentException(message);
        }

        if (!directory.isDirectory()) {
            String message = directory + " is not a directory";
            throw new IllegalArgumentException(message);
        }

        File[] files = directory.listFiles();
        if (files == null) { // null if security restricted
            throw new IOException("Failed to list contents of " + directory);
        }

        IOException exception = null;
        for (File file : files) {
            try {
                forceDelete(file);
            }
            catch (IOException ioe) {
                exception = ioe;
            }
        }

        if (null != exception) {
            throw exception;
        }
    }

    // -----------------------------------------------------------------------
    /**
     * Deletes a directory recursively.
     *
     * @param directory
     *            directory to delete
     * @throws IOException
     *             in case deletion is unsuccessful
     */
    public static void deleteDirectory(File directory) throws IOException {
        if (!directory.exists()) {
            return;
        }

        cleanDirectory(directory);

        if (!directory.delete()) {
            String message = "Unable to delete directory " + directory + ".";
            throw new IOException(message);
        }
    }

    /**
     * Deletes a file. If file is a directory, delete it and all
     * sub-directories.
     * <p>
     * The difference between File.delete() and this method are:
     * <ul>
     * <li>A directory to be deleted does not have to be empty.</li>
     * <li>You get exceptions when a file or directory cannot be deleted.
     * (java.io.File methods returns a boolean)</li>
     * </ul>
     *
     * @param file
     *            file or directory to delete, must not be {@code null}
     * @throws NullPointerException
     *             if the directory is {@code null}
     * @throws FileNotFoundException
     *             if the file was not found
     * @throws IOException
     *             in case deletion is unsuccessful
     */
    public static void forceDelete(File file) throws IOException {
        if (file.isDirectory()) {
            deleteDirectory(file);
        }
        else {
            boolean filePresent = file.exists();
            if (!file.delete()) {
                if (!filePresent) {
                    throw new FileNotFoundException("File does not exist: "
                            + file);
                }
                String message = "Unable to delete file: " + file;
                throw new IOException(message);
            }
        }
    }

    /**
     * Deletes a file, never throwing an exception. If file is a directory,
     * delete it and all sub-directories.
     * <p>
     * The difference between File.delete() and this method are:
     * <ul>
     * <li>A directory to be deleted does not have to be empty.</li>
     * <li>No exceptions are thrown when a file or directory cannot be deleted.</li>
     * </ul>
     *
     * @param file
     *            file or directory to delete, can be {@code null}
     * @return {@code true} if the file or directory was deleted, otherwise
     *         {@code false}
     *
     */
    public static boolean deleteQuietly(File file) {
        if (file == null) {
            return false;
        }
        try {
            if (file.isDirectory()) {
                cleanDirectory(file);
            }
        }
        catch (Exception ignored) {
        }

        try {
            return file.delete();
        }
        catch (Exception ignored) {
            return false;
        }
    }

    /**
     * Makes a directory, including any necessary but nonexistent parent
     * directories. If a file already exists with specified name but it is
     * not a directory then an IOException is thrown.
     * If the directory cannot be created (or does not already exist)
     * then an IOException is thrown.
     *
     * @param directory
     *            directory to create, must not be {@code null}
     * @throws NullPointerException
     *             if the directory is {@code null}
     * @throws IOException
     *             if the directory cannot be created or the file already exists
     *             but is not a directory
     */
    public static void forceMkdir(File directory) throws IOException {
        if (directory.exists()) {
            if (!directory.isDirectory()) {
                String message = "File " + directory + " exists and is "
                        + "not a directory. Unable to create directory.";
                throw new IOException(message);
            }
        }
        else {
            if (!directory.mkdirs()) {
                // Double-check that some other thread or process hasn't made
                // the directory in the background
                if (!directory.isDirectory()) {
                    String message = "Unable to create directory " + directory;
                    throw new IOException(message);
                }
            }
        }
    }

    /**
     * Returns the size of the specified file or directory. If the provided
     * {@link File} is a regular file, then the file's length is returned.
     * If the argument is a directory, then the size of the directory is
     * calculated recursively. If a directory or subdirectory is security
     * restricted, its size will not be included.
     *
     * @param file
     *            the regular file or directory to return the size
     *            of (must not be {@code null}).
     *
     * @return the length of the file, or recursive size of the directory,
     *         provided (in bytes).
     *
     * @throws NullPointerException
     *             if the file is {@code null}
     * @throws IllegalArgumentException
     *             if the file does not exist.
     *
     */
    public static long sizeOf(File file) {

        if (!file.exists()) {
            String message = file + " does not exist";
            throw new IllegalArgumentException(message);
        }

        if (file.isDirectory()) {
            return sizeOfDirectory(file);
        }
        else {
            return file.length();
        }

    }

    /**
     * Counts the size of a directory recursively (sum of the length of all
     * files).
     *
     * @param directory
     *            directory to inspect, must not be {@code null}
     * @return size of directory in bytes, 0 if directory is security
     *         restricted, a negative number when the real total
     *         is greater than {@link Long#MAX_VALUE}.
     * @throws NullPointerException
     *             if the directory is {@code null}
     */
    public static long sizeOfDirectory(File directory) {
        checkDirectory(directory);

        final File[] files = directory.listFiles();
        if (files == null) { // null if security restricted
            return 0L;
        }
        long size = 0;

        for (final File file : files) {

            size += sizeOf(file);
            if (size < 0) {
                break;

            }

        }

        return size;
    }

    /**
     * Checks that the given {@code File} exists and is a directory.
     *
     * @param directory
     *            The {@code File} to check.
     * @throws IllegalArgumentException
     *             if the given {@code File} does not exist or is not a
     *             directory.
     */
    private static void checkDirectory(File directory) {
        if (!directory.exists()) {
            throw new IllegalArgumentException(directory + " does not exist");
        }
        if (!directory.isDirectory()) {
            throw new IllegalArgumentException(directory
                    + " is not a directory");
        }
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
App相关→AppUtils.java 安装App installApp 卸载指定包名的App uninstallApp 获取当前App信息 getAppInfo 获取所有已安装App信息 getAllAppsInfo 根据包名判断App是否安装 isInstallApp 打开指定包名的App openAppByPackageName 打开指定包名的App应用信息界面 openAppInfo 可用来做App信息分享 shareAppInfo 判断当前App处于前台还是后台 isAppBackground 常量相关→ConstUtils.java 存储相关常量 时间相关常量 正则相关常量 转换相关→ConvertUtils.java→Test 每1个byte转为2个hex字符 bytes2HexString 每2个hex字符转为1个byte hexString2Bytes charArr转byteArr chars2Bytes byteArr转charArr bytes2Chars 设备相关→DeviceUtils.java 获取设备MAC地址 getMacAddress 获取设备厂商,如Xiaomi getManufacturer 获取设备型号,如MI2SC getModel 编码解码相关→EncodeUtils.java→Test URL编码 urlEncode URL解码 urlDecode Base64编码 base64Encode base64Encode2String Base64解码 base64Decode Base64URL安全编码 base64UrlSafeEncode Html编码 htmlEncode Html解码 htmlDecode 加密解密相关→EncryptUtils.java→Test MD2加密 encryptMD2ToString encryptMD2 MD5加密 encryptMD5ToString encryptMD5 SHA1加密 encryptSHA1ToString encryptSHA1 SHA224加密 encryptSHA224ToString encryptSHA224 SHA256加密 encryptSHA256ToString encryptSHA256 SHA384加密 encryptSHA384ToString encryptSHA384 SHA512加密 encryptSHA512ToString encryptSHA512 获取文件的MD5校验码 encryptMD5File2String encryptMD5File DES加密后转为Base64编码 encryptDES2Base64 DES加密后转为16进制 encryptDES2HexString DES加密 encryptDES DES解密Base64编码密文 decryptBase64DES DES解密16进制密文 decryptHexStringDES DES解密 decryptDES 3DES加密后转为Base64编码 encrypt3DES2Base64 3DES加密后转为16进制 encrypt3DES2HexString 3DES加密 encrypt3DES 3DES解密Base64编码密文 decryptBase64_3DES 3DES解密16进制密文 decryptHexString3DES 3DES解密 decrypt3DES AES加密后转为Base64编码 encryptAES2Base64 AES加密后转为16进制 encryptAES2HexString AES加密 encryptAES AES解密Base64编码密文 decryptBase64AES AES解密16进制密文 decryptHexStringAES AES解密 decryptAES 文件相关→FileUtils.java→Test 根据文件路径获取文件 getFileByPath 判断文件是否存在 isFileExists 判断是否是目录 isDir 判断是否是文件 isFile 判断目录是否存在,不存在则判断是否创建成功 createOrExistsDir 判断文件是否存在,不存在则判断是否创建成功 createOrExistsFile 判断文件是否存在,存在则在创建之前删除 createFileByDeleteOldFile 复制目录 copyDir 复制文件 copyFile 移动目录 moveDir 移动文件 moveFile 删除目录 deleteDir 删除文件 deleteFile 获取目录下所有文件 listFilesInDir 获取目录下所有文件包括子目录 listFilesIn
### 回答1: `fastjson` 提供了 `JSON.toJSONString()` 方法可以将 Java 对象转换成 JSON 字符串,也提供了 `JSON.toJavaObject()` 方法可以将 JSON 字符串转换成 Java 对象。 示例代码: ```java // 将 Java 对象转换成 JSON 字符串并写入文件 User user = new User("Tom", 18); String jsonString = JSON.toJSONString(user); File file = new File("user.json"); try (PrintWriter writer = new PrintWriter(file)) { writer.write(jsonString); } // 从文件中读取 JSON 字符串并转换成 Java 对象 String jsonStringFromFile = FileUtils.readFileToString(file, StandardCharsets.UTF_8); User userFromFile = JSON.parseObject(jsonStringFromFile, User.class); ``` 其中 `User` 是一个自定义的 Java ,`FileUtils` 是 `org.apache.commons.io.FileUtils` ,用于读取文件内容。请确保在使用 `FileUtils` 前添加相关依赖包。 ### 回答2: Java中的fastToJsonString和file是两个不同的概念。 fastToJsonString是指将Java对象转换为JSON字符串的方法。在Java中,我们可以使用各种库和框架来实现这个功能,比如Gson、Jackson等。fastToJsonString的作用是将一个Java对象快速转换为JSON格式的字符串,以便于在网络传输、存储或与其他系统进行数据交互。这个方法通常会将Java对象的属性值按照JSON的格式进行序列化,并返回一个字符串结果。 而fileJava中用于表示文件的。在Java中,我们可以通过File来操作文件,比如创建文件、读取文件内容、写入文件内容等。File提供了一系列的方法来帮助我们对文件进行操作,比如创建文件夹、删除文件、重命名文件等。通过File,我们可以很方便地读取和写入文件的内容,从而实现文件的读写操作。 因此,fastToJsonString和file是两个不同的概念和用法。fastToJsonString是用于将Java对象转换为JSON字符串的方法,而file是用于表示和操作文件的。在实际开发中,我们可以根据需要同时使用这两个概念来进行数据的处理和操作。 ### 回答3: java中的fastToJsonString和file都是与处理数据和文件相关的功能。 fastToJsonString是一个用于将Java对象快速转换为JSON字符串的方法。在Java中,我们经常需要在处理数据时将对象转换为JSON格式,以便进行数据传输和存储。fastToJsonString方法采用高效的算法和优化技巧,能够在转换过程中提高性能和效率。它可以直接将Java对象转换为JSON字符串,省去了手动拼接JSON字符串的麻烦和繁琐。使用fastToJsonString方法,我们只需将Java对象作为参数传入,即可得到对应的JSON字符串,非常方便快捷。 另外,Javafile是用于处理文件和文件夹的相关操作的。我们可以使用file来创建、删除、重命名文件或文件夹,以及获取文件的属性和信息等。file提供了一系列方法来对文件进行操作,比如判断文件是否存在、判断是否是文件或文件夹、获取文件大小等。同时,通过file还可以获取文件的输入流或输出流,方便读写文件的内容。file的使用对于文件的管理和操作非常方便,可以满足我们对文件的多种需求。 综上所述,fastToJsonString和file都是Java中用于处理数据和文件的功能。fastToJsonString可以快速将Java对象转换为JSON字符串,方便进行数据处理与存储;file则提供了丰富的方法,用于文件和文件夹的管理和操作。在开发过程中,掌握这两个功能将大大提高代码的效率和可靠性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值