java文件操作01--创建文件夹(2)

java文件操作01–创建文件夹(1)

使用java nio提供的Files工具类将常用的创建文件夹和创建文件的方法提供成为一个工具类:

文件夹创建:

createDirs()

  • 传入Path
  • 传入uri
  • 传入String

文件创建

createFile()

  • 传入Path
  • 传入uri
  • 传入String
  • 传入File
public class FileUtil {

    public static boolean createDirs( Path path ){
        try {
            if (!Files.exists(path)){
                Path directories = Files.createDirectories(path);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return Files.exists(path);
        }
    }

    public static boolean createDirs( URI uri ){
        return createDirs(Paths.get(uri));
    }

    public static boolean createDirs( String path ){
        return createDirs(Paths.get(path));
    }

    public static boolean createFile( File file ){
        try {
            if ( createDirs(file.getParent()) ){
                Files.createFile(file.toPath());
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return Files.exists( file.toPath() );
        }
    }

    public static boolean createFile( URI uri ){
        return createFile(Paths.get(uri));
    }

    public static boolean createFile( String path ){
        return createFile(Paths.get(path));
    }

    public static boolean createFile( Path path ){
        try {
            if ( createDirs(path.getParent()) ){
                Files.createFile(path);
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return Files.exists( path );
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34955471/article/details/106845929
今日推荐