您的位置:首页 > 其它

自我学习记录1--nio的文件操作

2018-04-13 15:22 363 查看
import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.nio.charset.Charset;

import java.nio.charset.StandardCharsets;

import java.nio.file.DirectoryStream;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

1.获取文件的编码格式

public static Charset getCS(String FilesName) {
Charset cs = null;
try {
InputStream inputStream = new FileInputStream(FilesName);
byte[] head = new byte[3];
inputStream.read(head);
inputStream.close();
if (head[0] == -17 && head[1] == -69 && head[2] == -65)
{
cs = StandardCharsets.UTF_8;
}
cs = StandardCharsets.ISO_8859_1;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return cs;
}


2.检查文件是否存在

public static boolean exitsFile(String filePath,String fileName){
Path dir = Paths.get(filePath);
Path path = null;
try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir,fileName)){
for(Path p:stream){
path = p.getFileName();
}
} catch (IOException e) {
e.printStackTrace();
}
return (path != null);
}


3.touch a new file

public static void touch(String fileName,String filePath) throws IOException
{
boolean flag = exitsFile(filePath, fileName);
Path path = Paths.get(filePath + fileName);
if (flag)
{
Files.delete(path);
}
Files.createFile(path);
}


4.find a file

public static void findInAllDir(String rootPath)
{
Path path = Paths.get(rootPath);
try {
Files.walkFileTree(path, new FileVisitTree());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static class FileVisitTree extends SimpleFileVisitor<Path>
{
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes arg1)
{
if (file.toString().contains("[keyWord]"))
{
//do something with the file
}
return FileVisitResult.CONTINUE;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  自我学习