java中File类使用简介说明
下文笔者讲述java中File类的功能示例说明,如下所示:
package IO;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
public class PathFilesDemo {
public static void main(String[] args) {
/*
* java265.com 示例分享
*/
File file = new File("D:\\test\\java265.txt");
//path
Path p1= Paths.get("D:\\test","java265.txt");
System.out.println(p1);
Path p2=file.toPath();
System.out.println(p2);
Path p3= FileSystems.getDefault().getPath("D:\\test","java265.txt");
System.out.println(p3);
/**
* Files工具类
*/
Path p4=Paths.get("D:\\test","java265.txt");
String info="hhhhhhh";
//写文件
try {
Files.write(p4,info.getBytes(), StandardOpenOption.APPEND);
System.out.println("写成功");
} catch (IOException e) {
e.printStackTrace();
}
//读文件
try {
byte[] bytes=Files.readAllBytes(p4);
System.out.println(new String(bytes));
System.out.println("读取成功");
} catch (IOException e) {
e.printStackTrace();
}
//复制文件
try {
Files.copy(p3,Paths.get("D:\\test\\java265-2.txt"), StandardCopyOption.replace_EXISTING);
System.out.println("复制文件成功");
} catch (IOException e) {
e.printStackTrace();
}
//移动文件
try {
Files.move(p3,Paths.get("d:\\"),StandardCopyOption.REPLACE_EXISTING);
System.out.println("移动文件成功");
} catch (IOException e) {
e.printStackTrace();
}
//删除文件
try {
Files.delete(p3);//static boolean deleteIfExists(Path path)
System.out.println("删除文件成功");
} catch (IOException e) {
e.printStackTrace();
}
//创建新目录,除了最后一个部件,其他必须是已存在的
try {
Files.createDirectory(Paths.get("D:\\"));
//Files.createDirectories(path);//创建路径中的中间目录,能创建不存在的中间部件
System.out.println("创建目录成功");
} catch (IOException e) {
e.printStackTrace();
}
//创建一个空文件,检查文件存在,如果已存在则抛出异常而检查文件存在是原子性的,
//因此在此过程中无法执行文件创建操作
try {
Files.createFile(Paths.get("d:\\java265-3.txt"));
System.out.println("创建文件成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


