String 与 ByteBuffer的互转
// 1 将字符串转为ByteBuffer
ByteBuffer buffer = ByteBuffer.allocate(20);
buffer.put("hello".getBytes());
System.out.println(buffer);
// 2 Charset
ByteBuffer buffer1 = StandardCharsets.UTF_8.encode("hello");
System.out.println(buffer1);
// 3 wrap
ByteBuffer buffer2 = ByteBuffer.wrap("hello".getBytes());
System.out.println(buffer2);
// 将ByteBuffer转为String
String mes = StandardCharsets.UTF_8.decode(buffer2).toString();
System.out.println(mes);
Paths 与 Files 的使用
创建一级目录
try {
Path path = Paths.get("hello");
Files.createDirectory(path);
} catch (IOException e) {
e.printStackTrace();
}
如果目录已存在,会跑出异常 FileAireadyExistsException
不能创建多级目录,否在会抛出NosuchFileException
创建多级目录
try {
Path path = Paths.get("hello/3/3/2");
Files.createDirectories(path);
} catch (IOException e) {
e.printStackTrace();
}
文件拷贝
try {
Path path = Paths.get("hello/1.txt");
Path target = Paths.get("hello/2.txt");
Files.copy(path,target);
} catch (IOException e) {
e.printStackTrace();
}
如果文件已经存在,则会抛异常FileAlreadyExistsException
如果希望覆盖,可以用重载的方法
try {
Path path = Paths.get("hello/1.txt");
Path target = Paths.get("hello/2.txt");
Files.copy(path,target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
遍历文件
AtomicInteger dirCount = new AtomicInteger();
AtomicInteger fileCount = new AtomicInteger();
try {
Files.walkFileTree( Paths.get("/Users/mac/IdeaProjects/spring-demos"),new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
dirCount.getAndIncrement();
return super.preVisitDirectory(dir, attrs);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.toString().endsWith(".java")) {
fileCount.getAndIncrement();
System.out.println(file);
}
return super.visitFile(file, attrs);
}
});
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("目录:" + dirCount + " java:" + fileCount);
删除非空文件夹
try {
Files.walkFileTree(Paths.get("/Users/mac/IdeaProjects/spring-demos/hello"),new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return super.visitFile(file, attrs);
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return super.postVisitDirectory(dir, exc);
}
});
} catch (IOException e) {
e.printStackTrace();
}
文件复制
String source ="/Users/mac/Desktop/111";
String target ="/Users/mac/Desktop/222";
try {
Files.walk(Paths.get(source)).forEach(path -> {
try {
String targetName = path.toString().replace(source, target);
if (Files.isDirectory(path)) {
Files.createDirectory(Paths.get(targetName));
}else if(Files.isRegularFile(path)){
Files.copy(path,Paths.get(targetName));
}
} catch (Exception e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}