⽂件操作之File和Path
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<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-rw-rw-");
// FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(perms);
try {
if(!ists(target2))
} catch (IOException e) {
e.printStackTrace();
}
windows下不⽀持PosixFilePermission来指定rwx权限。
5)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("测试⽂件写操作");
writer.flush();
writer.close();
} catch (IOException e1) {
e1.printStackTrace();
}
7)遍历⼀个⽂件夹:
Path dir = ("D:\\webworkspace");
try(DirectoryStream<Path> stream = wDirectoryStream(dir)){
for(Path e : stream){
System.out.FileName());
}
}catch(IOException e){
}
try (Stream<Path> stream = Files.("C:/"))){
Iterator<Path> 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<Path> result = new LinkedList<Path>();
Files.walkFileTree(startingDir, new FindJavaVisitor(result));
System.out.println("result.size()=" + result.size());
}
private static class FindJavaVisitor extends SimpleFileVisitor<Path>{
private List<Path> result;
public FindJavaVisitor(List<Path> 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<Path> result = new LinkedList<Path>();
Files.walkFileTree(startingDir, new FindJavaVisitor(result));
System.out.println("result.size()=" + result.size());
System.out.println("done.");
}
private static class FindJavaVisitor extends SimpleFileVisitor<Path>{
private List<Path> result;
public FindJavaVisitor(List<Path> 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<Path> result = new LinkedList<Path>();
Files.walkFileTree(startingDir, new FindJavaVisitor(result));
System.out.println("result.size()=" + result.size());
System.out.println("done.");
}
private static class FindJavaVisitor extends SimpleFileVisitor<Path>{
private List<Path> result;
public FindJavaVisitor(List<Path> 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"));
if(!("C://TEST")))
<("C://"));
// ("C://"));
} catch (IOException e) {
e.printStackTrace();
}
注意创建⽬录和⽂件ateDirectories 和 ateFile不能混⽤,必须先有⽬录,才能在⽬录中创建⽂件。2)⽂件复制:
从⽂件复制到⽂件:py(Path source, Path target, CopyOption options);
从输⼊流复制到⽂件:py(InputStream in, Path target, CopyOption options);
从⽂件复制到输出流:py(Path source, OutputStream out);
try {
<("C://TEST"));
if(!("C://TEST")))
<("C://"));
// ("C://"));
<("C://my.ini"), System.out);
<("C://my.ini"), ("C://my2.ini"), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
3)遍历⼀个⽬录和⽂件夹上⾯已经介绍了:wDirectoryStream , Files.walkFileTree
4)读取⽂件属性:
Path zip = (uri);
System.out.LastModifiedTime(zip));
System.out.println(Files.size(zip));
System.out.println(Files.isSymbolicLink(zip));
System.out.println(Files.isDirectory(zip));
System.out.adAttributes(zip, "*"));
5)读取和设置⽂件权限:
Path profile = ("/home/digdeep/.profile");
PosixFileAttributes attrs = adAttributes(profile, PosixFileAttributes.class);// 读取⽂件的权限
Set<PosixFilePermission> posixPermissions = attrs.permissions();
posixPermissions.clear();
String owner = attrs.owner().getName();
String perms = String(posixPermissions);
System.out.format("%s %s%n", owner, perms);
posixPermissions.add(PosixFilePermission.OWNER_READ);
posixPermissions.add(PosixFilePermission.GROUP_READ);
posixPermissions.add(PosixFilePermission.OTHERS_READ);
posixPermissions.add(PosixFilePermission.OWNER_WRITE);
Files.setPosixFilePermissions(profile, posixPermissions); // 设置⽂件的权限
Files类简直强⼤的⼀塌糊涂,⼏乎所有⽂件和⽬录的相关属性,操作都有想要的api来⽀持。这⾥懒得再继续介绍了,详细参见 jdk8 的⽂档。
⼀个实际例⼦:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class StringTools {
public static void main(String[] args) {
try {
BufferedReader reader = ("C:\\Members.sql"), StandardCharsets.UTF_8);
BufferedWriter writer = ("C:\\"), StandardCharsets.UTF_8);
String str = null;
while ((str = adLine()) != null) {
if (str != null && str.indexOf(", CAST(0x") != -1 && str.indexOf("AS DateTime)") != -1) {
String newStr = str.substring(0, str.indexOf(", CAST(0x")) + ")";
writer.write(newStr);
}
}
writer.flush();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
java创建文件}
场景是,sql server导出数据时,会将 datatime 导成16进制的binary格式,形如:, CAST(0x0000A2A500FC2E4F AS DateTime))
所以上⾯的程序是将最后⼀个 datatime 字段导出的 , CAST(0x0000A2A500FC2E4F AS DateTime) 删除掉,⽣成新的不含有datetime字段值的sql 脚本。⽤来导⼊到mysql中。
做到半途,其实有更好的⽅法,使⽤sql yog可以很灵活的将sql server中的表以及数据导⼊到mysql中。使⽤sql server⾃带的导出数据的功
能,反⽽不好处理。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论