Tips for using: Explain file operations in Java programming

Source: Internet
Author: User
Tags copy count readline tostring stringbuffer
Programming | skills | detailed

I. Obtaining information entered by the console user

       
        
         
        /** *//** Gets the information entered by the console user     * @return     * @throws ioexception     /public    String Getinputmessage () throws IOException ... {        System.out.println ("Please enter your command:");        byte buffer[]=new byte[1024];        int count=system.in.read (buffer);        Char[] ch=new char[count-2];//last two digits as Terminator, delete do not for        (int i=0;i<count-2;i++)            ch[i]= (char) buffer[i];        String Str=new string (ch);        return str;    }
       
        

Can return the user input information, the disadvantage is not support Chinese input, need further improvement.

Two. copy files

1. Copying files in a file flow manner

       
        
         
        /** *//** file streams copy files     * @param src File source directory *     @param dest File destination directory     * @throws ioexception/public    void cop Yfile (String src,string dest) throws IOException ... {        fileinputstream in=new fileinputstream (SRC);        File File=new file (dest);        if (!file.exists ())            file.createnewfile ();        FileOutputStream out=new fileoutputstream (file);        int C;        byte buffer[]=new byte[1024];        while ((C=in.read (buffer))!=-1 ... {for            (int i=0;i<c;i++)                out.write (Buffer[i]);                }        In.close ();        Out.close ();    }
       
        

This method has been tested to support Chinese processing and can be replicated in a variety of formats such as Txt,xml,jpg,doc

Three. Write a document

1. Use PrintStream to write files

       
        
         
        /** *//**     * File Output Example * * Public    void Printstreamdemo () ... {        Try ... {            FileOutputStream out=new fileoutputstream ("D:/test.txt");            PrintStream p=new PrintStream (out);            for (int i=0;i<10;i++)                p.println (' is ' +i+ ' line ');        } catch (FileNotFoundException e) ... {            e.printstacktrace ();        }    }
       
        

2. Use StringBuffer to write files

       
        
         
        public void Stringbufferdemo () throws IOException ... {        file File=new file ("/root/sms.log");        if (!file.exists ())            file.createnewfile ();        FileOutputStream out=new FileOutputStream (file,true);                for (int i=0;i<10000;i++) ... {            stringbuffer sb=new stringbuffer ();            Sb.append ("This is the first" +i+ "line: The various methods described earlier are not closed, why is always a strange problem");            Out.write (Sb.tostring (). GetBytes ("Utf-8"));                Out.close ();    }
       
        

This method can be used to set the code to effectively solve the Chinese problem.

Four. File renaming

       
        
         
        /** *//** File Rename *     @param path file directory     * @param oldname  Original file name     * @param newname New file name    */public void R Enamefile (String path,string oldname,string newname) ... {        if (!oldname.equals (newname)) ... {//new file name is not the same as previous filename, it is necessary to            rename File Oldfile=new file (path+ "/" +oldname);            File Newfile=new file (path+ "/" +newname);            if (newfile.exists ())//If there is already a file in this directory and the new file name is the same, you are not allowed to rename                System.out.println (newname+) already exists! ");            else ... {                Oldfile.renameto (newfile);}}}             
       
        

Five. Transfer file directory

The staging file directory is not the same as copying the file, the copy file exists after both directories are replicated, and the staging file directory is transferred, only the file exists in the new directory.

       
        
         
        /** *//** Transfer file directory     * @param filename filename     * @param oldpath Old directory *     @param newpath new directory     * @param cover if a new directory exists and transfers text If a file with the same filename is      overwritten with the new directory file, Cover=true will overwrite the original file, or not operation     /public    void Changedirectory (String filename, String oldpath,string Newpath,boolean cover) ... {        if (!oldpath.equals (NewPath)) ... {            file Oldfile=new file (oldpath+ "/" +filename);            File Newfile=new file (newpath+ "/" +filename);            if (newfile.exists ()) ... {//If there is already a transfer file                if (cover)//overwrite                    Oldfile.renameto (newfile) in the pending directory;                else                    System.out.println ("already exists under the new directory:" +filename);            }            else ... {                Oldfile.renameto (newfile);}}}           
       
        

Six. Read the document

1. read files using FileInputStream

       
        
         
        /** *//** Read File     * @param path     * @return     * @throws ioexception    /public String Fileinputstreamdemo ( String path) throws IOException ... {        file File=new file (path);        if (!file.exists () | | File.isdirectory ())            throw new FileNotFoundException ();        FileInputStream fis=new fileinputstream (file);        byte[] buf = new byte[1024];        StringBuffer sb=new StringBuffer ();        while ((Fis.read (BUF))!=-1) ... {            sb.append (new String (BUF));                Buf=new byte[1024];//rebuild, avoid and last read data repeat} return        sb.tostring ();    }
       
        

2. Using BufferedReader to read

In IO operations, using BufferedReader and bufferedwriter efficiencies would be a bit higher

       
        
         
        /** *//** Read File     * @param path     * @return     * @throws ioexception    /public String Bufferedreaderdemo ( String path) throws IOException ... {        file File=new file (path);        if (!file.exists () | | File.isdirectory ())            throw new FileNotFoundException ();        BufferedReader br=new BufferedReader (new FileReader (file));        String Temp=null;        StringBuffer sb=new StringBuffer ();        Temp=br.readline ();        while (Temp!=null) ... {            sb.append (temp+ "");            Temp=br.readline ();        }        return sb.tostring ();    }
       
        

3. read XML files using dom4j

       
        
         
        /** *//** read XML file from directory *     @param path file directory     * @return *     @throws documentexception *     @throws IOException     * * Public    Document readXml (String path) throws Documentexception, IOException ... {        file File=new file (path);        BufferedReader BufferedReader = new BufferedReader (new FileReader (file));        Saxreader Saxreader = new Saxreader ();        Document document = (document) Saxreader.read (BufferedReader);        Bufferedreader.close ();        return document;    }
       
        

Seven. Create a file (folder)

1. Create a folder/** *//** create a folder

       
        
         
        * @param path  directory     *    /public void Createdir (String path) ... {        file Dir=new file (path);        if (!dir.exists ())            dir.mkdir ();    }
       
        

2. Create a new file/** *//** create a new file

       
        
         
        * @param path Directory     * @param filename filename     * @throws ioexception    /public void CreateFile (String path,st Ring filename) throws IOException ... {        file File=new file (path+ "/" +filename);        if (!file.exists ())            file.createnewfile ();    }
       
        

Eight. Delete file (directory)

1. Delete Files

       
        
         
        /** Delete File     * @param path directory     * @param filename     /public    void Delfile (String path,string filename) ... {        file File=new file (path+ "/" +filename);        if (File.exists () &&file.isfile ())            file.delete ();    }
       
        

2. Delete Directory

To delete a directory using the Delete () method of the file class, you must ensure that there are no files or subdirectories under that directory, or the deletion fails, so in practice, we delete the directory, and we have to delete all subdirectories and files in the directory recursively, and then delete the directory.

       
        
         
        /** Recursive Delete folder     * @param path     /public    void Deldir (String path) ... {        file Dir=new file (path);        if (dir.exists ()) ... {            file[] tmp=dir.listfiles ();            for (int i=0;i<tmp.length;i++) ... {                if (tmp[i].isdirectory ()) ... {                    Deldir (path+ "/" +tmp[i].getname ());                }                else ... {                    tmp[i].delete ();                }            }            Dir.delete ();        }    
       
        


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.