一:创建文件或目录。
/**
* 创建文件或目录
*/
private static void createFileOrDir() {
try {
// 创建新目录,除了最后一个部件,其他必须是存在的
Files.createDirectory(Paths.get("F:/test"));
// 创建路径中的中间目录,能创建不存在的中间部件
Files.createDirectories(Paths.get("F:/test/test"));
// 创建文件及相关目录
Path path = Paths.get("F:/test/testbak.txt");
Files.createDirectories(path.getParent());
Files.createFile(path);
} catch (IOException e) {
e.printStackTrace();
}
}
二:删除文件
/**
* 删除文件
*/
private static void deleteFile() {
Path p = Paths.get("F:/test.txt");
try {
Files.delete(p);// 用static boolean deleteIfExists(Path path)方法比较好
System.out.println("删除成功");
} catch (IOException e) {
e.printStackTrace();
}
}
三:移动文件
/**
* 移动文件
*/
private static void moveFile() {
Path pSrc = Paths.get("F:/test.txt");
Path pDest = Paths.get("E:/test.txt");
try {
Files.move(pSrc, pDest, StandardCopyOption.REPLACE_EXISTING);
System.out.println("移动成功");
} catch (IOException e) {
e.printStackTrace();
}
}
四:复制文件
/**
* 复制文件
*/
private static void copyFile() {
Path pSrc = Paths.get("F:/test.txt");
Path pDest = Paths.get("F:/testbak.txt");
try {
Files.copy(pSrc, pDest, StandardCopyOption.REPLACE_EXISTING);
System.out.println("复制成功");
} catch (IOException e) {
e.printStackTrace();
}
}
五:获取文件字节
/**
* 从文件读取数据
*/
private static void readFromFile() {
Path p = Paths.get("F:/", "test.txt");
try {
byte[] bytes = Files.readAllBytes(p);
System.out.println(new String(bytes));
} catch (IOException e) {
e.printStackTrace();
}
}
六:按行读取文件
/**
* 从文件按行读取数据
*/
private static void readByLineFromFile() {
Path path = Paths.get("F:/", "test.txt");
try {
// 方式1
List<String> lines = Files.lines(path).collect(Collectors.toList());
System.out.println(lines);
// 方式2
BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
String str = null;
while((str = reader.readLine()) != null){
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
七:向文件写入数据
/**
* 向文件写入数据
*/
private static void write2File() {
// 获得路径
Path path = Paths.get("F:/", "test.txt");
String info = "I love java really,你喜欢什么?";
try {
// 方式1
Files.write(path, info.getBytes("utf8"), StandardOpenOption.APPEND);
// 方式2
BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8);
writer.write(info );
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
八:获取文件路径
/**
* 获得文件路径的几种方法
*/
private static void getFilePath() {
File file = new File("F:/test.txt");
// Path
Path p1 = Paths.get("F:/", "test.txt");// F:\test.txt
System.out.println(p1);
Path p2 = file.toPath();
System.out.println(p2);
Path p3 = FileSystems.getDefault().getPath("F:/", "test.txt");
System.out.println(p3);
}