javapath类_基于javaFiles类和Paths类的⽤法(详解)
Java7中⽂件IO发⽣了很⼤的变化,专门引⼊了很多新的类:
import java.nio.file.DirectoryStream;
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.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
.
.....等等,来取代原来的基于java.io.File的⽂件IO操作⽅式.
1. Path就是取代File的
A Path represents a path that is hierarchical and composed of a sequence of directory and file name elements separated by a special separator or delimiter.
Path⽤于来表⽰⽂件路径和⽂件。可以有多种⽅法来构造⼀个Path对象来表⽰⼀个⽂件路径,或者⼀个⽂件:
1)⾸先是final类Paths的两个static⽅法,如何从⼀个路径字符串来构造Path对象:
Path path = ("C:/", "Xmp");
Path path2 = ("C:/Xmp");
URI u = ate("file:///C:/Xmp/dd");
Path p = (u);
2)FileSystems构造:
Path path3 = Default().getPath("C:/", "access.log");
3)File和Path之间的转换,File和URI之间的转换:
File file = new File("C:/my.ini");
Path p1 = Path();
4)创建⼀个⽂件:
Path target2 = ("C:\\");
// Set perms = PosixFilePermissions.fromString("rw-rw-rw-");
// FileAttribute> attrs = PosixFilePermissions.asFileAttribute(perms);
try {
if(!ists(target2))
} catch (IOException e) {
e.printStackTrace();
}
windows下不⽀持PosixFilePermission来指定rwx权限。
wBufferedReader读取⽂件:
try {
// Charset.forName("GBK")
BufferedReader reader = ("C:\\my.ini"), StandardCharsets.UTF_8);
String str = null;
while((str = adLine()) != null){
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}
可以看到使⽤ wBufferedReader 远⽐原来的FileInputStream,然后BufferedReader包装,等操作简单的多了。这⾥如果指定的字符编码不对,可能会抛出异常 MalformedInputException ,或者读取到了乱码:
java.nio.charset.MalformedInputException: Input length = 1
at java.nio.charset.CoderResult.throwException(CoderResult.java:281)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:339)
at sun.nio.ad(StreamDecoder.java:178)
at java.ad(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.adLine(BufferedReader.java:324)
at java.adLine(BufferedReader.java:389)
in.Test.main(Test.java:79)
6)⽂件写操作:
try {
BufferedWriter writer = ("C:\\my2.ini"), StandardCharsets.UTF_8);
writer.write("测试⽂件写操作");
mysql下载之后是个文件夹writer.flush();
writer.close();
} catch (IOException e1) {
e1.printStackTrace();
}
7)遍历⼀个⽂件夹:
Path dir = ("D:\\webworkspace");
try(DirectoryStream stream = wDirectoryStream(dir)){
for(Path e : stream){
System.out.FileName());
}
}catch(IOException e){
}
try (Stream stream = Files.("C:/"))){
Iterator ite = stream.iterator();
while(ite.hasNext()){
Path pp = ();
System.out.FileName());
}
} catch (IOException e) {
e.printStackTrace();
}
上⾯是遍历单个⽬录,它不会遍历整个⽬录。遍历整个⽬录需要使⽤:Files.walkFileTree 8)遍历整个⽂件⽬录:
public static void main(String[] args) throws IOException{
Path startingDir = ("C:\\apache-tomcat-8.0.21");
List result = new LinkedList();
Files.walkFileTree(startingDir, new FindJavaVisitor(result));
System.out.println("result.size()=" + result.size());
}
private static class FindJavaVisitor extends SimpleFileVisitor{
private List result;
public FindJavaVisitor(List result){
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs){
String().endsWith(".java")){
result.FileName());
}
return FileVisitResult.CONTINUE;
}
}
来⼀个实际例⼦:
public static void main(String[] args) throws IOException {
Path startingDir = ("F:\\upload\\images"); // F:\\upload\\images\\2\\20141206
List result = new LinkedList();
Files.walkFileTree(startingDir, new FindJavaVisitor(result));
System.out.println("result.size()=" + result.size());
System.out.println("done.");
}
private static class FindJavaVisitor extends SimpleFileVisitor{
private List result;
public FindJavaVisitor(List result){
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs){
String filePath = File().getAbsolutePath();
if(filePath.matches(".*_[1|2]{1}\\.(?i)(jpg|jpeg|gif|bmp|png)")){
try {
Files.deleteIfExists(file);
} catch (IOException e) {
e.printStackTrace();
}
result.FileName());
} return FileVisitResult.CONTINUE;
}
}
将⽬录下⾯所有符合条件的图⽚删除掉:filePath.matches(".*_[1|2]{1}\\.(?i)(jpg|jpeg|gif|bmp|png)") public static void main(String[] args) throws IOException {
Path startingDir = ("F:\\111111\\upload\\images"); // F:\111111\\upload\\images\\2\\20141206 List result = new LinkedList();
Files.walkFileTree(startingDir, new FindJavaVisitor(result));
System.out.println("result.size()=" + result.size());
System.out.println("done.");
}
private static class FindJavaVisitor extends SimpleFileVisitor{
private List result;
public FindJavaVisitor(List result){
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs){
String filePath = File().getAbsolutePath();
int width = 224;
int height = 300;
StringUtils.substringBeforeLast(filePath, ".");
String newPath = StringUtils.substringBeforeLast(filePath, ".") + "_1."
+ StringUtils.substringAfterLast(filePath, ".");
try {
} catch (IOException e) {
e.printStackTrace();
return FileVisitResult.CONTINUE;
}
result.FileName());
return FileVisitResult.CONTINUE;
}
}
为⽬录下的所有图⽚⽣成指定⼤⼩的缩略图。a.jpg 则⽣成 a_1.jpg
2. 强⼤的java.nio.file.Files
1)创建⽬录和⽂件:
try {
<("C://TEST"));
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论