Java file IO operation should abandon file embrace path and files

Source: Internet
Author: User
Tags file copy

The file IO in Java7 has changed a lot and has introduced many new classes 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;

...... And so on, to replace the original Java.io.File-based file IO operation mode.

1. Path is the replacement of file

A Path represents a path that's hierarchical and composed of a sequence of directory and file name elements separated by A special separator or delimiter.

path is used to represent the file path and file . There are several ways to construct a path object to represent a file path, or a file:

1) first, the final class paths two static methods, how to construct the path object from a path string:

        Path PATH = Paths.get ("c:/", "XMP");         = Paths.get ("C:/XMP");                 = Uri.create ("File:///C:/Xmp/dd");                 = 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:

        New File ("C:/my.ini");         = 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 under Windows to specify RWX permissions.

5) Files.newbufferedreader Read file:

        Try {//            charset.forname ("GBK")            BufferedReader reader = Files.newbufferedreader ( Paths.get ("C:\\my.ini"), standardcharsets.utf_8);             NULL ;              while NULL ) {                System.out.println (str);            }         Catch (IOException e) {            e.printstacktrace ();        }

You can see the use of files.newbufferedreader far more than the original FileInputStream, and then BufferedReader packaging, and so the operation is much simpler.

If the specified character is not encoded, it may throw an exception malformedinputexception , or read garbled:

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 operation:

        Try {            = 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) {                    }

Above is the traversal of a single directory, which does not traverse the entire directory. Traversing the entire directory requires the use of: Files.walkfiletree

8) traverse the entire file directory:

     Public Static voidMain (string[] args)throwsioexception{Path Startingdir= Paths.get ("c:\\apache-tomcat-8.0.21"); List<Path> result =NewLinkedlist<path>(); Files.walkfiletree (Startingdir,Newfindjavavisitor (result)); System.out.println ("Result.size () =" +result.size ()); }        Private Static classFindjavavisitorextendsSimplefilevisitor<path>{        PrivateList<path>result;  PublicFindjavavisitor (list<path>result) {             This. result =result; } @Override Publicfilevisitresult visitfile (Path file, Basicfileattributes attrs) {if(File.tostring (). EndsWith (". Java") {Result.add (File.getfilename ()); }            returnfilevisitresult.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 Creating directories and files 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 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) traversing a directory and folder has been described 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));            " *"));

5) Read and set file permissions:

Path profile = Paths.get ("/home/digdeep/.profile"); Posixfileattributes Attrs= Files.readattributes (profile, posixfileattributes.class)///Read the file permissions Set<PosixFilePermission> 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 for a file

The files class is simply a powerful mess, with almost all of the file and directory related properties, operations have the desired API to support. This is too lazy to continue the introduction, see the JDK8 documentation in detail.

Java file IO operation should abandon file embrace path and files

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.