All Java File Operations

Source: Internet
Author: User

1. Obtain information entered by the console user

/*** // ** Obtain the information entered by the console user * @ return * @ throws ioexception */Public String getinputmessage () throws ioexception... {system. out. println ("Enter your command:"); byte buffer [] = new byte [1024]; int COUNT = system. in. read (buffer); char [] CH = new char [count-2]; // the last two digits are the Terminator. Do not delete for (INT I = 0; I <count-2; I ++) CH [I] = (char) buffer [I]; string STR = new string (CH); Return STR ;}

The user input information can be returned. The disadvantage is that Chinese input is not supported and further improvement is needed.
Ii. Copy an object

1. copy a file as a file stream

/*** // Copy the file * @ Param SRC file source directory * @ Param DEST file destination directory * @ throws ioexception */Public void copyfile (string SRC, string DEST) throws ioexception... {fileinputstream in = new fileinputstream (SRC); 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 is tested and supports Chinese processing and can be copied to multiple formats, such as txt, XML, JPG, and Doc.
3. Write files

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 ("this is" + I + "line");} catch (filenotfoundexception e )... {e. printstacktrace ();}}

2. Use stringbuffer to write files

Public void stringbufferdemo () throws ioexception... {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 line" + I + ": the methods described earlier are not used. Why is it always a strange problem?"); out. write (sb. tostring (). getbytes ("UTF-8");} Out. close ();}

This method can be used to set the encoding to effectively solve Chinese problems.

Iv. File rename

/*** // Rename the * @ Param path file directory * @ Param oldname original file name * @ Param newname new file name */Public void renamefile (string path, string oldname, string newname )... {If (! Oldname. equals (newname ))... {// It is necessary to rename the file oldfile = new file (path + "/" + oldname) because the new file name is different from the previous one ); file newfile = new file (path + "/" + newname); If (newfile. exists () // if there is already a file in the directory with the same name as the new file, system cannot be renamed. out. println (newname + "already exists! "); Else... {oldfile. renameto (newfile );}}}

5. Transfer file directory

The transfer file directory is not the same as the copy file. The copy file exists in both directories after the copy, but the transfer file directory exists only in the new directory after the transfer.

/*** // ** Transfer file directory * @ Param filename file name * @ Param oldpath old directory * @ Param newpath new directory * @ Param cover if the new directory exists and transfers files when a file with the same file name exists, whether to overwrite the files in the new directory. "cover = true" will overwrite the original file. Otherwise, do not operate */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 the file to be transferred already exists in the directory to be transferred if (cover) // overwrite the oldfile. renameto (newfile); else system. out. println ("already exists in the new directory:" + filename);} else... {oldfile. renameto (newfile );}}}

6. Read files

1. Use fileinputstream to read files

2. Read data using bufferedreader

In Io operations, bufferedreader and bufferedwriter are more efficient.

3. Use dom4j to read XML files

/*** // ** Read the XML file from the directory * @ Param path file directory * @ return * @ throws documentexception * @ throws ioexception */public document readxml (string path) throws disable entexception, ioexception... {file = new file (PATH); bufferedreader = new bufferedreader (New filereader (File); saxreader = new saxreader (); document = (document) saxreader. read (bufferedreader); bufferedreader. close (); Return document ;}

7. 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 file name * @ throws ioexception */Public void createfile (string path, string filename) throws ioexception... {file = new file (path + "/" + filename); If (! File. exists () file. createnewfile ();}

8. delete files (directories)

1. delete an object

* ** // ** Delete the file * @ Param path directory * @ Param filename file name */Public void delfile (string path, string filename )... {file = new file (path + "/" + filename); If (file. exists () & file. isfile () file. delete ();}

2. delete a directory
To delete a directory using the delete () method of the file class, you must ensure that there are no files or subdirectories in the directory; otherwise, the deletion fails. Therefore, in actual applications, we need to delete the directory, you must recursively Delete All subdirectories and files in the directory before deleting the directory.

/*** // ** Recursively Delete the 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 ();}}

3. Read files

/*** // ** Read the file * @ Param path * @ return * @ throws ioexception */Public String bufferedreaderdemo (string path) throws ioexception... {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 ();}


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.