Java file IO operation should discard file hug paths and files

Source: Internet
Author: User
Tags file copy readline

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");        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 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);            String str = null;            while ((str = reader.readline ()) = 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 {            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> ite = Stream.iterator ();            while (Ite.hasnext ()) {                Path pp = Ite.next ();                System.out.println (Pp.getfilename ());            }        } catch (IOException e) {            e.printstacktrace ();        }

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 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;        }    }

To 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> Resul        T        Public Findjavavisitor (list<path> result) {This.result = result; } @Override Public Filevisitresult visitfile (Path file, Basicfileattributes attrs) {Strin                   G 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 eligible pictures below 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\\i    Mages ");        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> Resul        T        Public Findjavavisitor (list<path> result) {This.result = result; } @Override Public Filevisitresult visitfile (Path file, Basicfileattributes attrs) {Strin            G 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 thumbnails of the specified size for all pictures under 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 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));            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< 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.

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 (); }    }}

Transferred from: https://www.cnblogs.com/digdeep/p/4478734.html

Java file IO operation should discard file hug paths and files

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.