0%

基于1-8的Base64和文件的转换及1-7的Files类

文章字数:511,阅读全文大约需要2分钟

文件转Base64

1
2
3
4
5
6
7
8
9
10
11
12
public String encryptToBase64(String filePath) {
if (filePath == null) {
return null;
}
try {
byte[] b = Files.readAllBytes(Paths.get(filePath));
return Base64.getEncoder().encodeToString(b);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

Files、Paths类是JDK7里加入的,读取文件不再需要调用IO包里的FileInputStream,简单便捷。字符串参数filePath是文件的路径。

首先是将文件读成二进制码,然后通过Base64.getEncoder().encodeToString()方法将二进制码转换为Base64值。

Base64转文件

1
2
3
4
5
6
7
8
9
10
11
public String decryptByBase64(String base64, String filePath) {
if (base64 == null && filePath == null) {
return "生成文件失败,请给出相应的数据。";
}
try {
Files.write(Paths.get(filePath), Base64.getDecoder().decode(base64),StandardOpenOption.CREATE);
} catch (IOException e) {
e.printStackTrace();
}
return "指定路径下生成文件成功!";
}

Files.write()方法轻松将文件写入指定位置

Path类

1.7之后引入了java.nio.file包取代原来基于java.io.File的文件IO操作
位置:

  • java.nio.file.Files
  • java.nio.file.Path
  1. 获取path

    1
    2
    3
    4
    5
    6
    7
    Path path;
    //1.绝对路径
    path = Paths.get("c:\\test.txt");
    //2.相对路径
    path = Paths.get("/demo/test.txt");
    //3.通过FileSystems
    path = FileSystems.getDefault().getPath("c:\\test.txt");
  2. FilePath转换

    1
    2
    3
    4
    5
    6
    7
    File file = new file("c:\\xxx.txt");
    //文件转Path
    Path path = file.toPath();
    //Path转File
    path.toFile();
    //File转uri
    file.toURI();
  3. Path信息

    1
    2
    3
    4
    5
    6
    7
    8
    9
    Path path = Paths.get("D:\\demo\text.txt");
    System.out.println("文件名:" + path.getFileName());
    System.out.println("名称元素的数量:" + path.getNameCount());
    System.out.println("父路径:" + path.getParent());
    System.out.println("根路径:" + path.getRoot());
    System.out.println("是否是绝对路径:" + path.isAbsolute());
    //startsWith()方法的参数既可以是字符串也可以是Path对象
    System.out.println("是否是以为给定的路径D:开始:" + path.startsWith("D:\\") );
    System.out.println("该路径的字符串形式:" + path.toString());

File类

  1. 文件是否存在

    1
    2
    3
    4
    Path path = Paths.get("D:\\demo.txt");
    boolean pathExists = Files.exists(path,new LinkOption[]{
    LinkOption.NOFOLLOW_LINKS
    });//数组内的NOFOLLOW_LINKS代表不包含符合链接文件
  2. 创建文件/文件夹

    1
    2
    3
    4
    5
    6
    7
    Path target2 = Paths.get("C:\\demo.txt");
    try{
    if(!Files.exists(target2))
    Files.createFile(target2);
    }catch(IOException e){
    e.printStackTrace();
    }

    Files.createDirectory()创建文件夹,上级目录不存在报错
    Files.createDirectorys()创建文件夹,上级目录不存在则创建上级目录

  3. 删除文件或目录

    1
    2
    3
    4
    5
    6
    Path path = Paths.get("data/subdir/logging-moved.properties");
    try {
    Files.delete(path);
    } catch (IOException e) {
    e.printStackTrace();
    }
  4. 复制文件到另一个位置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    Path sourcePath = Paths.get("data/logging.properties");
    Path destinationPath = Paths.get("data/logging-copy.properties");
    try {
    Files.copy(sourcePath, destinationPath);
    } catch(FileAlreadyExistsException e) {
    //文件已经存在
    } catch (IOException e) {
    e.printStackTrace();
    }

    还可以直接覆盖目标文件

    1
    2
    Files.copy(sourcePath, destinationPath,
    StandardCopyOption.REPLACE_EXISTING);
  5. 获取文件属性

    1
    2
    3
    4
    5
    6
    Path path = Paths.get("D:\\XMind\\bcl-java.txt");
    System.out.println(Files.getLastModifiedTime(path));
    System.out.println(Files.size(path));
    System.out.println(Files.isSymbolicLink(path));
    System.out.println(Files.isDirectory(path));
    System.out.println(Files.readAttributes(path, "*"));
  6. 遍历一个文件夹

    1
    2
    3
    4
    5
    6
    7
    8
    Path dir = Paths.get("D:\\Java");
    try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir)){
    for(Path e : stream){
    System.out.println(e.getFileName());
    }
    }catch(IOException e){
    //...
    }
  7. 遍历整个文件目录
    walkFileTree接受一个path和FileVisitor,path是遍历的目录,FileVistor则是一个接口,每次遍历都会被调用,需要自己实现。
    SimpleFileVisitor是默认实现类,将接口所有方法都做了空实现。

    1
    2
    3
    4
    //地址
    Path startingDir = Paths.get("D:\\demo");
    //调用
    Files.walkFileTree(startingDir, new FindJavaVisitor());

    FindJavaVisitor.java

    1
    2
    3
    4
    5
    6
    7
    public class FindJavaVisitor extends SimpleFileVisitor<Path>{
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs){
    //do...
    return FileVisitResult.CONTINUE;
    }
    }