Java File Operations

Source: Internet
Author: User

Android file name security skills

Public static Boolean isfilenameok (String filepath){
Return Pattern. Compile ("[\ W % +,./= _-] +"). matcher (filepath). Matches ();
}

Public static Boolean isfilenameok (File){
Return Pattern. Compile ("[\ W % +,./= _-] +"). matcher (file. getpath (). Matches ();
}

1. Obtain information entered by the console user

/***** // Obtain 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, delete not

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 a file as a file stream

* @ Param SRC file source directory

* @ Param DEST the target directory of the file

* @ Throws ioexception

*/

Public void copyfile (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 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 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 above are not used. Why is it always a strange question ");

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 file

* @ 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 a new file name that is different from the previous one.

File oldfile = new file (path + "/" + oldname );

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, rename is not allowed

System. 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 the file directory

* @ Param filename: File Name

* @ Param oldpath old directory

* @ Param newpath: new directory

* @ Param cover if there is a file with the same file name as the transfer file in the new directory, whether to overwrite the file in the new directory, cover = true will overwrite the original file; otherwise, no operation will be performed.

*/

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 it is in the directory to be transferred, the file to be transferred already exists

If (cover) // Overwrite

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

/***** // Read the 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 FCM = new fileinputstream (File );

Byte [] Buf = new byte [1, 1024];

Stringbuffer sb = new stringbuffer ();

While (FCM. Read (BUF ))! =-1 )...{

SB. append (new string (BUF ));

Buf = new byte [1024]; // regenerate to avoid duplication with the data read last time

}

Return sb. tostring ();

}

2. Read data using bufferedreader

In Io operations, bufferedreader and bufferedwriter are more efficient.

/***** // Read the 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. Use dom4j to read XML files

/***** // Read the XML file from the directory

* @ Param path file directory

* @ Return

* @ Throws define entexception

* @ Throws ioexception

*/

Public document readxml (string path) throws into entexception, ioexception ...{

File file = new file (PATH );

Bufferedreader = new bufferedreader (New filereader (File ));

Saxreader = new saxreader ();

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

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

}< br>
8. delete a file (directory)

1. delete a file or *** delete a 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 ();

}< br>
2. delete directory
to delete a directory by using the delete () method of the file class, you must ensure that there are no files or subdirectories in the directory; otherwise, deletion fails, therefore, in practical applications, to delete a directory, you must recursively Delete All subdirectories and files under the Directory and then delete the directory. /*** // ** Recursively delete a 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 If (TMP [I]. isdirectory ())... {
deldir (path + "/" + TMP [I]. getname ();

}< br>
else... {
TMP [I]. delete ();

}< br>
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.