Java File I/O operations should discard File embraces Path and Files, iopath
The file IO in Java 7 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. PosixFilePermission;
Import java. nio. file. attribute. PosixFilePermissions;
... To replace the original File io Operation Method Based on java. IO. File.
1. Path is used to replace File
APathRepresents 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 indicate the file Path and file. There can be multiple methods to construct a Path object to represent a file Path or a file:
1) The first is the two static methods of the final Paths class. 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 structure:
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(); }
In windows, PosixFilePermission is not supported to specify the rwx permission.
5) Files. newBufferedReader:
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(); }
We can see that the use of Files. newBufferedReader is much simpler than the original FileInputStream, and then the BufferedReader is packaged.
If the specified character encoding is incorrect, it may throw MalformedInputException or read garbled characters:
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 write operations:
Try {BufferedWriter writer = Files. newBufferedWriter (Paths. get ("C :\\ my2.ini"), StandardCharsets. UTF_8); writer. write ("test file write operations"); 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> ite = stream.iterator(); while(ite.hasNext()){ Path pp = ite.next(); System.out.println(pp.getFileName()); } } catch (IOException e) { e.printStackTrace(); }
The above is to traverse a single directory, it will not traverse the entire directory. To traverse the entire directory, you need to use: Files. filetree
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; } }
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 creating directories and Files. createDirectories and Files. createFile cannot be mixed. You must first have a directory to create Files in the directory.
2) File Replication:
Copy From file to file: Files. copy (Path source, Path target, CopyOption options );
Copy from input stream to 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) traverse a directory and folder as described above: Files. newDirectoryStream, Files. Program filetree
4) read file attributes:
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); // Set <PosixFilePermission> posixPermissions = attrs. permissions (); posixPermissions. clear (); String owner = attrs. owner (). getName (); String perms = PosixFilePermissions. toString (posixPermissions); System. out. format ("% 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); // sets the object ACL.
The Files class is incredibly powerful. Almost all file and directory attributes and operations are supported by the desired api. I am too lazy to continue here. For more information, see the jdk8 documentation.