Java Io operations (read/write, append, delete, move, copy, etc)

Source: Internet
Author: User

1. Read File Content in multiple ways.

1. Read File Content by byte
2. Read File Content by character
3. Read File Content by row
4. Randomly Read File Content

Import java. Io. bufferedreader;
Import java. Io. file;
Import java. Io. fileinputstream;
Import java. Io. filereader;
Import java. Io. ioexception;
Import java. Io. inputstream;
Import java. Io. inputstreamreader;
Import java. Io. randomaccessfile;
Import java. Io. reader;
Public class readfromfile {
/**
* Reading files in bytes is usually used to reading binary files, files, sounds, images, and other files.
* @ Param filename file name
*/
Public static void readfilebybytes (string filename ){
File file = new file (filename );
Inputstream in = NULL;
Try {
System. Out. println ("Read File Content in bytes, read one byte at a time :");
// Read one byte at a time
In = new fileinputstream (File );
Int tempbyte;
While (tempbyte = in. Read ())! =-1 ){
System. Out. Write (tempbyte );
}
In. Close ();
} Catch (ioexception e ){
E. printstacktrace ();
Return;
}
Try {
System. Out. println ("Read File Content in bytes, read multiple bytes at a time :");
// Read multiple bytes at a time
Byte [] tempbytes = new byte [1, 100];
Int byteread = 0;
In = new fileinputstream (filename );
Readfromfile. showavailablebytes (in );
// Read multiple bytes into the byteread array. byteread is the number of bytes read at a time.
While (byteread = in. Read (tempbytes ))! =-1 ){
System. Out. Write (tempbytes, 0, byteread );
}
} Catch (exception E1 ){
E1.printstacktrace ();
} Finally {
If (in! = NULL ){
Try {
In. Close ();
} Catch (ioexception E1 ){
}
}
}
}
/**
* Reads a file in characters. It is often used for reading text, numbers, and other types of files.
* @ Param filename: File Name
*/
Public static void readfilebychars (string filename ){
File file = new file (filename );
Reader reader = NULL;
Try {
System. Out. println ("Read File Content in character units, read one byte at a time :");
// Read one character at a time
Reader = new inputstreamreader (New fileinputstream (File ));
Int tempchar;
While (tempchar = reader. Read ())! =-1 ){
// For Windows, when the/R/n characters are together, a line break is displayed.
// If the two characters are displayed separately, the rows are changed twice.
// Therefore, block/R or block/n. Otherwise, there will be a lot more blank lines.
If (char) tempchar )! = '/R '){
System. Out. Print (char) tempchar );
}
}
Reader. Close ();
} Catch (exception e ){
E. printstacktrace ();
}
Try {
System. Out. println ("Read File Content in characters, read multiple bytes at a time :");
// Read multiple characters at a time
Char [] tempchars = new char [30];
Int charread = 0;
Reader = new inputstreamreader (New fileinputstream (filename ));
// Read multiple characters into the character array. charread is the number of characters read at a time.
While (charread = reader. Read (tempchars ))! =-1 ){
// Disable/R is not displayed.
If (charread = tempchars. Length) & (tempchars [tempchars. Length-1]! = '/R ')){
System. Out. Print (tempchars );
} Else {
For (INT I = 0; I <charread; I ++ ){
If (tempchars [I] = '/R '){
Continue;
} Else {
System. Out. Print (tempchars [I]);
}
}
}
}

} Catch (exception E1 ){
E1.printstacktrace ();
} Finally {
If (reader! = NULL ){
Try {
Reader. Close ();
} Catch (ioexception E1 ){
}
}
}
}
/**
* Reads files in behavior units. It is often used to read row-oriented formatted files.
* @ Param filename: File Name
*/
Public static void readfilebylines (string filename ){
File file = new file (filename );
Bufferedreader reader = NULL;
Try {
System. Out. println ("read the file content in the unit of action, read the entire row at a time :");
Reader = new bufferedreader (New filereader (File ));
String tempstring = NULL;
Int line = 1;
// Read a row at a time until null is the end of the file.
While (tempstring = reader. Readline ())! = NULL ){
// Display the row number
System. Out. println ("line" + LINE + ":" + tempstring );
Line ++;
}
Reader. Close ();
} Catch (ioexception e ){
E. printstacktrace ();
} Finally {
If (reader! = NULL ){
Try {
Reader. Close ();
} Catch (ioexception E1 ){
}
}
}
}
/**
* Random reading of File Content
* @ Param filename: File Name
*/
Public static void readfilebyrandomaccess (string filename ){
Randomaccessfile randomfile = NULL;
Try {
System. Out. println ("randomly reading a file :");
// Open a random file stream in read-only mode
Randomfile = new randomaccessfile (filename, "R ");
// File length, number of bytes
Long filelength = randomfile. Length ();
// Start position of the read object
Int beginindex = (filelength> 4 )? 4: 0;
// Move the start position of the read object to the beginindex position.
Randomfile. Seek (beginindex );
Byte [] bytes = new byte [10];
Int byteread = 0;
// Read 10 bytes at a time. If the file content is less than 10 bytes, read the remaining bytes.
// Assign the number of bytes read at a time to byteread
While (byteread = randomfile. Read (bytes ))! =-1 ){
System. Out. Write (bytes, 0, byteread );
}
} Catch (ioexception e ){
E. printstacktrace ();
} Finally {
If (randomfile! = NULL ){
Try {
Randomfile. Close ();
} Catch (ioexception E1 ){
}
}
}
}
/**
* Display the remaining bytes in the input stream
* @ Param in
*/
Private Static void showavailablebytes (inputstream in ){
Try {
System. Out. println ("number of bytes in the Current byte input stream:" + in. Available ());
} Catch (ioexception e ){
E. printstacktrace ();
}
}

Public static void main (string [] ARGs ){
String filename = "C:/temp/newtemp.txt ";
Readfromfile. readfilebybytes (filename );
Readfromfile. readfilebychars (filename );
Readfromfile. readfilebylines (filename );
Readfromfile. readfilebyrandomaccess (filename );
}
}

 

2. append the content to the end of the file

Import java. Io. filewriter;
Import java. Io. ioexception;
Import java. Io. randomaccessfile;

/**
* Append the content to the end of the file.
*/
Public class appendtofile {

/**
* Method A append a file: Use randomaccessfile
* @ Param filename: File Name
* @ Param content: Append content
*/
Public static void appendmethoda (string filename, string content ){
Try {
// Open a random access file stream in read/write mode
Randomaccessfile randomfile = new randomaccessfile (filename, "RW ");
// File length, number of bytes
Long filelength = randomfile. Length ();
// Move the Write File pointer to the end of the file.
Randomfile. Seek (filelength );
Randomfile. writebytes (content );
Randomfile. Close ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}
/**
* Method B append a file: Use filewriter
* @ Param filename
* @ Param content
*/
Public static void appendmethodb (string filename, string content ){
Try {
// Open a file writer. The second parameter true in the constructor indicates that the file is written as an append object.
Filewriter writer = new filewriter (filename, true );
Writer. Write (content );
Writer. Close ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}

Public static void main (string [] ARGs ){
String filename = "C:/temp/newtemp.txt ";
String content = "New append! ";
// Append an object by method
Appendtofile. appendmethoda (filename, content );
Appendtofile. appendmethoda (filename, "APPEND end./N ");
// Display the File Content
Readfromfile. readfilebylines (filename );
// Append an object by Method B
Appendtofile. appendmethodb (filename, content );
Appendtofile. appendmethodb (filename, "APPEND end./N ");
// Display the File Content
Readfromfile. readfilebylines (filename );
}
}

Operations of three files

Import java. Io .*;

/**
* Fileoperate. Java
* File Operations
* @ Author Yang Cai http://blog.sina.com.cn/m/yangcai
* File operation 1.0
*/

Public class fileoperate
{

Public fileoperate ()
{
}
/**
* Create a directory
*/
Public void newfolder (string folderpath)
{
Try
{
String filepath = folderpath;
Filepath = filepath. tostring ();
File myfilepath = new file (filepath );
If (! Myfilepath. exists ())
{
Myfilepath. mkdir ();
}
System. Out. println ("Directory creation succeeded ");
}
Catch (exception E)
{
System. Out. println ("Directory creation error ");
E. printstacktrace ();
}
}
/**
* Create a file
*/
Public void newfile (string filepathandname, string filecontent)
{
Try
{
String filepath = filepathandname;
Filepath = filepath. tostring ();
File myfilepath = new file (filepath );
If (! Myfilepath. exists ())
{
Myfilepath. createnewfile ();
}
Filewriter resultfile = new filewriter (myfilepath );
Printwriter myfile = new printwriter (resultfile );
String strcontent = filecontent;
Myfile. println (strcontent );
Resultfile. Close ();
System. Out. println ("file creation succeeded ");
}
Catch (exception E)
{
System. Out. println ("Directory creation error ");
E. printstacktrace ();
}
}
/**
* Delete an object
*/
Public void delfile (string filepathandname)
{
Try
{
String filepath = filepathandname;
Filepath = filepath. tostring ();
File mydelfile = new file (filepath );
Mydelfile. Delete ();
System. Out. println ("the file is successfully deleted ");
}
Catch (exception E)
{
System. Out. println ("File Deletion error ");
E. printstacktrace ();
}
}
/**
* Delete A folder
*/
Public void delfolder (string folderpath)
{
Try
{
Delallfile (folderpath); // delete all contents
String filepath = folderpath;
Filepath = filepath. tostring ();
File myfilepath = new file (filepath );
If (myfilepath. Delete () {// delete an empty folder
System. Out. println ("deleting Folders" + folderpath + "successfully executed ");
} Else {
System. Out. println ("deleting Folders" + folderpath + "operation failed ");
}
}
Catch (exception E)
{
System. Out. println ("Folder deletion error ");
E. printstacktrace ();
}
}
/**
* Delete all files in the folder
* @ Param path string folder path such as C:/fqf
*/
Public void delallfile (string path)
{
File file = new file (PATH );
If (! File. exists ())
{
Return;
}
If (! File. isdirectory ())
{
Return;
}
String [] templist = file. List ();
File temp = NULL;
For (INT I = 0; I <templist. length; I ++)
{
If (path. endswith (file. separator ))
{
Temp = new file (path + templist [I]);
}
Else
{
Temp = new file (path + file. Separator + templist [I]);
}
If (temp. isfile ())
{
Temp. Delete ();
}
If (temp. isdirectory ())
{
// Delallfile (path + "/" + templist [I]); // delete the files in the folder first
Delfolder (path + file. separatorchar + templist [I]); // Delete the empty folder
}
}
System. Out. println ("the file is successfully deleted ");
}
/**
* Copy a single file
* @ Param oldpath string original file path, for example, C:/fqf.txt
* @ Param newpath: the copied string path is F:/fqf.txt.
*/
Public void copyfile (string oldpath, string newpath)
{
Try
{
Int bytesum = 0;
Int byteread = 0;
File oldfile = new file (oldpath );
If (oldfile. exists ())
{
// When the file exists
Inputstream instream = new fileinputstream (oldpath); // read the original file
Fileoutputstream FS = new fileoutputstream (newpath );
Byte [] buffer = new byte [1444];
While (byteread = instream. Read (buffer ))! =-1)
{
Bytesum + = byteread; // file size in bytes
System. Out. println (bytesum );
FS. Write (buffer, 0, byteread );
}
Instream. Close ();
}
System. Out. println ("Folder deletion successful ");
}
Catch (exception E)
{
System. Out. println ("An error occurred while copying a single file ");
E. printstacktrace ();
}
}
/**
* Copy the entire folder.
* @ Param oldpath string original file path, for example, C:/fqf
* @ Param newpath: path after string copying, for example, F:/fqf/ff.
*/
Public void copyfolder (string oldpath, string newpath)
{
Try
{
(New file (newpath). mkdirs (); // create a new folder if the folder does not exist
File a = new file (oldpath );
String [] file = A. List ();
File temp = NULL;
For (INT I = 0; I <file. length; I ++)
{
If (oldpath. endswith (file. separator ))
{
Temp = new file (oldpath + file [I]);
}
Else
{
Temp = new file (oldpath + file. Separator + file [I]);
}
If (temp. isfile ())
{
Fileinputstream input = new fileinputstream (temp );
Fileoutputstream output = new fileoutputstream (newpath + "/" +
(Temp. getname (). tostring ());
Byte [] B = new byte [1, 1024*5];
Int Len;
While (LEN = input. Read (B ))! =-1)
{
Output. Write (B, 0, Len );
}
Output. Flush ();
Output. Close ();
Input. Close ();
}
If (temp. isdirectory ())
{
// For subfolders
Copyfolder (oldpath + "/" + file [I], newpath + "/" + file [I]);
}
}
System. Out. println ("Copy folder succeeded ");
}
Catch (exception E)
{
System. Out. println ("An error occurred while copying the entire folder ");
E. printstacktrace ();
}
}
/**
* Move a file to a specified directory
* @ Param oldpath string such as: C:/fqf.txt
* @ Param newpath string such as: D:/fqf.txt
*/
Public void movefile (string oldpath, string newpath)
{
Copyfile (oldpath, newpath );
Delfile (oldpath );
}
/**
* Move a file to a specified directory
* @ Param oldpath string such as: C:/fqf.txt
* @ Param newpath string such as: D:/fqf.txt
*/
Public void movefolder (string oldpath, string newpath)
{
Copyfolder (oldpath, newpath );
Delfolder (oldpath );
}
Public static void main (string ARGs [])
{
String AA, BB;
Boolean exitnow = false;
System. Out. println ("to use this function, follow [1] function 1: create a directory ");
System. Out. println ("to use this function, follow [2] function 2: create a file ");
System. Out. println ("to use this function, follow [3] Function 3: delete a file ");
System. Out. println ("to use this function, press [4] function 4: delete a folder ");
System. Out. println ("to use this function, follow [5] function 5: delete all files in the folder ");
System. Out. println ("to use this function, press [6] Function 6: copy a file ");
System. Out. println ("to use this function, press [7] function 7: Copy all contents of the folder ");
System. Out. println ("to use this function, follow [8] function 8: Move files to the specified directory ");
System. Out. println ("to use this function, press [9] Function 9: Move a folder to a specified directory ");
System. Out. println ("use this function Please press [10] exit program ");
While (! Exitnow)
{
Fileoperate fo = new fileoperate ();
Try
{
Bufferedreader bin = new bufferedreader (New inputstreamreader (system. In ));
String A = bin. Readline ();
Int B = integer. parseint ();
Switch (B)
{
Case 1: system. Out. println ("if you have selected function 1, enter the directory name ");
AA = bin. Readline ();
Fo. newfolder (AA );
Break;
Case 2: system. Out. println ("you have selected feature 2. Enter the file name ");
AA = bin. Readline ();
System. Out. println ("Enter the content in" + AA + ");
BB = bin. Readline ();
Fo. newfile (AA, BB );
Break;
Case 3: system. Out. println ("you have selected feature 3. Enter the file name ");
AA = bin. Readline ();
Fo. delfile (AA );
Break;
Case 4: system. Out. println ("you have selected feature 4. Enter the file name ");
AA = bin. Readline ();
Fo. delfolder (AA );
Break;
Case 5: system. Out. println ("if you select feature 5, enter the file name ");
AA = bin. Readline ();
Fo. delallfile (AA );
Break;
Case 6: system. Out. println ("you have selected feature 6. Enter the file name ");
AA = bin. Readline ();
System. Out. println ("Enter the target file name ");
BB = bin. Readline ();
Fo. copyfile (AA, BB );
Break;
Case 7: system. Out. println ("you have selected function 7. Enter the source file name ");
AA = bin. Readline ();
System. Out. println ("Enter the target file name ");
BB = bin. Readline ();
Fo. copyfolder (AA, BB );
Break;
Case 8: system. Out. println ("you have selected feature 8. Enter the source file name ");
AA = bin. Readline ();
System. Out. println ("Enter the target file name ");
BB = bin. Readline ();
Fo. movefile (AA, BB );
Break;
Case 9: system. Out. println ("you have selected feature 9. Enter the source file name ");
AA = bin. Readline ();
System. Out. println ("Enter the target file name ");
BB = bin. Readline ();
Fo. movefolder (AA, BB );
Break;
Case 10: exitnow = true;
System. Out. println ("program ended, please exit ");
Break;
Default: system. Out. println ("input error. Enter the number between 1 and 10 ");
}
System. Out. println ("Please reselect feature ");
}
Catch (exception E)
{
System. Out. println ("incorrect input character or program error ");
}
}
}
}

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.