Java-文件的操作

Path

  • 对路径而已,路径分隔符,Unix文件系统是”/”,windows是”\”,以根部件开始的路径是绝对路径,否则是相对路径。
  • Path表示的是一个目录名序列,其后还可以跟着一个文件名
  • API java.nio.file.Paths 7
    • static Path get(String first, String …more),通过连接给定的字符串创建一个路径。
    • Path resovle(Path other) Path resolve(String other),如果other是绝对路径,那么就返回other;否则,返回通过连接this和other获取的路径
    • Path toAbsolutePath() 返回与该路径等价的绝对路径
    • Path getParent() 返回父路径,没有父路径,返回null
    • Path getFileName 返回该路径的最后一个部件
    • Path getRoot() 返回该路径的跟部件,没有返回null
    • toFile()从该路径中创建一个File对象

读写文件

Files类可以使普通文件操作更加的快捷。

//读取文件内容
byte[] bytes = Files.readAllBytes(path);
//如果想要将文件当作字符串处理。
String content = new String(bytes, charset);
//如果希望将文件当作行序列读入
List<String> lines = Files.readAllLines(path, charset);
//如果希望写出一个字符到文件
Files.wirte(path, content.getBytes(charset))

  • 以上的方法适合中等长度的文件,处理文件的长度比较大,或者是二进制文件,应该是流或者读入器/写出器
InputStream in = Files.newInputStream(path, options);
OutputStream out = Files.newOutputStream(path, options);
Reader in = Files.newBufferedReader(path, charset);
Writer out = Files.newBufferedWriter(path, charset, options);
  • 复制一个文件
    • Files.copy(fromPath, toPath);
  • 移动文件(即复制并删除原文件)
    • Files.move(fromPath, toPath);
  • 删除文件
    • Files.delete(path);
//创建新文件
 public static Path createFile(Path path, FileAttribute<?>... attrs)
 //创建新目录
 public static Path createDirectory(Path dir, FileAttribute<?>... attrs)
 //创建临时文件
  public static Path createTempFile(Path dir, String prefix,String suffix, FileAttribute<?>... attrs)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值