File IO in Java7 has undergone great changes, and many new classes have been introduced specifically:
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.PosixFilePermissions;
......Wait, to replace the original file IO operation method based on java.io.File.
1. Path replaces 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 is used to represent file paths and files. There are several ways to construct a Path object to represent a file path, or a file:
1) First of all, there are two static methods of the final class Paths. How to construct a Path object from a path string:
Path path = Paths.get("C:/", "Xmp"); Path path2 = Paths.get("C:/Xmp"); URI u = URI.create("file:///C:/Xmp/dd"); Path p = Paths.get(u);2) FileSystems construction:
Path path3 = FileSystems.getDefault().getPath("C:/", "access.log");3) Conversion between File and Path, conversion between File and URI:
File file = new File("C:/my.ini");Path p1 = file.toPath();p1.toFile();file.toURI();4) Create a file:
Path target2 = Paths.get("C://mystuff.txt");// Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-rw-rw-");// FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(perms);try { if(!Files.exists(target2))Files.createFile(target2);} catch (IOException e) { e.printStackTrace();}PosixFilePermission is not supported in Windows to specify rwx permissions.
5) Files.newBufferedReader reads the file:
try {// Charset.forName("GBK") BufferedReader reader = Files.newBufferedReader(Paths.get("C://my.ini"), StandardCharsets.UTF_8); String str = null; while((str = reader.readLine()) != null){ System.out.println(str); } } catch (IOException e) { e.printStackTrace(); }You can see that using Files.newBufferedReader is much easier than the original FileInputStream and then the BufferedReader package.
Here, if the specified character encoding is incorrect, an exception may be thrown, or a garbled code may be read:
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.cs.StreamDecoder.read(StreamDecoder.java:178) at java.io.InputStreamReader.read(InputStreamReader.java:184) at java.io.BufferedReader.fill(BufferedReader.java:161) at java.io.BufferedReader.readLine(BufferedReader.java:324) at java.io.BufferedReader.readLine(BufferedReader.java:389) at com.coin.Test.main(Test.java:79)
6) File writing operation:
try { BufferedWriter writer = Files.newBufferedWriter(Paths.get("C://my2.ini"), StandardCharsets.UTF_8); writer.write("Test file write operation"); writer.flush(); writer.close();} catch (IOException e1) { e1.printStackTrace();}7) Traverse a folder:
Path dir = Paths.get("D://webworkspace"); try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir)){ for(Path e : stream){ System.out.println(e.getFileName()); } }catch(IOException e){ } try (Stream<Path> stream = Files.list(Paths.get("C:/"))){ Iterator<Path> item = stream.iterator(); while(ite.hasNext()){ Path pp = item.next(); System.out.println(pp.getFileName()); } } catch (IOException e) { e.printStackTrace(); }The above is traversing a single directory, it does not traversing the entire directory. You need to use: Files.walkFileTree
8) Traverse the entire file directory:
public static void main(String[] args) throws IOException{ Path startingDir = Paths.get("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){ this.result = result; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs){ if(file.toString().endsWith(".java")){ result.add(file.getFileName()); } return FileVisitResult.CONTINUE; } }Let's take a practical example:
public static void main(String[] args) throws IOException { Path startingDir = Paths.get("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){ this.result = result; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs){ String filePath = file.toFile().getAbsolutePath(); if(filePath.matches(".*_[1|2]{1}//.(?i)(jpg|jpeg|gif|bmp|png)")){ try { Files.deleteIfExists(file); } catch (IOException e) { e.printStackTrace(); } result.add(file.getFileName()); } return FileVisitResult.CONTINUE; } }Delete all the qualified images in the directory: filePath.matches(".*_[1|2]{1}//.(?i)(jpg|jpeg|gif|bmp|png)")
public static void main(String[] args) throws IOException { Path startingDir = Paths.get("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){ this.result = result; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs){ String filePath = file.toFile().getAbsolutePath(); int width = 224; int height = 300; StringUtils.substringBeforeLast(filePath, "."); String newPath = StringUtils.substringBeforeLast(filePath, ".") + "_1." + StringUtils.substringAfterLast(filePath, "."); try { ImageUtil.zoomImage(filePath, newPath, width, height); } catch (IOException e) { e.printStackTrace(); return FileVisitResult.CONTINUE; } result.add(file.getFileName()); return FileVisitResult.CONTINUE; } }Generates a thumbnail of the specified size for all images in the directory. a.jpg generates a_1.jpg
2. Powerful java.nio.file.Files
1) Create directories and files:
try { Files.createDirectories(Paths.get("C://TEST")); if(!Files.exists(Paths.get("C://TEST"))) Files.createFile(Paths.get("C://TEST/test.txt"));// Files.createDirectories(Paths.get("C://TEST/test2.txt"));} catch (IOException e) { e.printStackTrace();}Note that the creation directory and file Files.createDirectories and Files.createFile cannot be mixed. You must have a directory before you can create files in the directory.
2) File copy:
Copy from file to file: Files.copy(Path source, Path target, CopyOption options);
Copy from the input stream to the file: Files.copy(InputStream in, Path target, CopyOption options);
Copy from file to output stream: Files.copy(Path source, OutputStream out);
try { Files.createDirectories(Paths.get("C://TEST")); if(!Files.exists(Paths.get("C://TEST"))) Files.createFile(Paths.get("C://TEST/test.txt"));// Files.createDirectories(Paths.get("C://TEST/test2.txt")); Files.copy(Paths.get("C://my.ini"), System.out); Files.copy(Paths.get("C://my.ini"), Paths.get("C://my2.ini"), StandardCopyOption.REPLACE_EXISTING); Files.copy(System.in, Paths.get("C://my3.ini"), StandardCopyOption.REPLACE_EXISTING);} catch (IOException e) { e.printStackTrace();}3) Iterate through a directory and folder. It has been introduced above: Files.newDirectoryStream, Files.walkFileTree
4) Read file properties:
Path zip = Paths.get(uri); System.out.println(Files.getLastModifiedTime(zip)); System.out.println(Files.size(zip)); System.out.println(Files.isSymbolicLink(zip)); System.out.println(Files.isDirectory(zip)); System.out.println(Files.readAttributes(zip, "*"));
5) Read and set file permissions:
Path profile = Paths.get("/home/digdeep/.profile"); PosixFileAttributes attrs = Files.readAttributes(profile, PosixFileAttributes.class);// Permission to read files Set<PosixFilePermissions> posixPermissions = attrs.permissions(); posixPermissions.clear(); String owner = attrs.owner().getName(); String perms = PosixFilePermissions.toString(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); // Set permissions of the fileThe Files class is simply powerful, and almost all related properties of files and directories have the desired API to support. I am too lazy to continue introducing it here, please refer to the documentation of jdk8 for details.
A practical example:
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 = Files.newBufferedReader(Paths.get("C://Members.sql"), StandardCharsets.UTF_8); BufferedWriter writer = Files.newBufferedWriter(Paths.get("C://Members3.txt"), StandardCharsets.UTF_8); String str = null; while ((str = reader.readLine()) != 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.newLine(); } } writer.flush(); writer.close(); } catch (Exception e) { e.printStackTrace(); } }}The scenario is that when SQL Server exports data, the datatime will be exported into a hexadecimal binary format, such as: CAST(0x0000A2A500FC2E4F AS DateTime))
Therefore, the above program exports the last datatime field, deletes CAST(0x0000A2A500FC2E4F AS DateTime) to generate a new SQL script that does not contain the datetime field value. Used to import into mysql.
Halfway through, there is actually a better way. Using SQL yog can flexibly import tables and data in SQL Server into mysql. Using the function of exporting data from SQL Server is difficult to deal with.
The above usage (detailed explanation) based on the Java Files class and Paths class is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.