Java io file operations (multiple reading methods-byte, character, line, random)

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 line 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 {/*** reads files in bytes. It is often used to read 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, 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 [100]; int byteread = 0; in = new FileInputStream (fileName); ReadFromFile. showAvailableBytes (in); // read multiple bytes into the byte 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 and is often used to read text, file * @ param fileName file name */public static void readFileByChars (String fileName) {File = new file (fileName); Reader reader = null; try {System. out. println ("Read file Content in characters, 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 two characters/r/n 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) {// also blocked/r does not show 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 the file in the unit of action, commonly 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 ("reads the content of a file in the unit of action, and reads 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) {}}}/*** Randomly Read File Content * @ param fileName file name */public static void readFileByRandomAccess (String fileName) {RandomAccessFile randomFile = null; try {System. out. println ("randomly read a file:"); // open a random access 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 = (fileLengt H> 4 )? 4: 0; // move the start position of the read file 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); ReadFromFil E. readFileByChars (fileName); ReadFromFile. readFileByLines (fileName); ReadFromFile. readFileByRandomAccess (fileName) ;}ii. 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 {/*** A method to append the file: use RandomAccessFile * @ param fileName file name * @ param content to Append content */public static void appendMethodA (String fileName, String c Ontent) {try {// open a random file stream, read/write RandomAccessFile randomFile = new RandomAccessFile (fileName, "rw"); // file length, 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: Use FileWriter * @ param fileName * @ param content */public static void appendMethodB (String fileName, String content) {try {// open a file writer. The second parameter in the constructor, true, indicates that the file is written as an append. FileWriter writer = new FileWriter (fileName, true); writer. write (content); writer. close ();} catc H (IOException e) {e. printStackTrace () ;}} public static void main (String [] args) {String fileName = "C:/temp/newTemp.txt"; String content = "new append! "; // Append the file AppendToFile by method. appendMethodA (fileName, content); AppendToFile. appendMethodA (fileName, "append end. /n "); // display the file content ReadFromFile. readFileByLines (fileName); // append the file AppendToFile by method B. appendMethodB (fileName, content); AppendToFile. appendMethodB (fileName, "append end. /n "); // display the file content ReadFromFile. readFileByLines (fileName) ;}} various operation classes of File 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 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 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 ("Successful file creation");} catch (Exception e) {System. out. println ("Directory creation error"); e. printStackTrace () ;}/ *** delete file */public void delFile (String filePathAndName) {try {String FilePath = filePathAndName; filePath = filePath. toString (); File myDelFile = new File (filePath); myDelFile. delete (); System. out. println ("Successful file deletion");} catch (Exception e) {System. out. println ("File Deletion error"); e. printStackTrace () ;}/ *** Delete folder */public void delFolder (String folderPath) {try {delAllFile (folderPath ); // After deleting all content, String filePath = folderPath; filePath = filePath. toString (); File myFilePath = new File (FilePath); if (myFilePath. delete () {// delete an empty folder System. out. println ("delete folder" + folderPath + "operation successful");} else {System. out. println ("delete folder" + folderPath + "operation failed") ;}} catch (Exception e) {System. out. println ("An error occurred while deleting Folders"); 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 File delFolder (path + File. separatorChar + tempList [I]); // delete an empty folder} System. out. println ("Successful file deletion");}/*** copy a single file * @ param oldPath String original file path such as: c: /fqf.txt * @ param newPath String: 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 FileOutputStre Am (newPath); byte [] buffer = new byte [1444]; while (byteread = inStream. read (buffer ))! =-1) {bytesum + = byteread; // number of bytes file size System. out. println (bytesum); fs. write (buffer, 0, byteread);} inStream. close ();} System. out. println ("Folder deletion succeeded");} catch (Exception e) {System. out. println ("An error occurred while copying a single file"); e. printStackTrace () ;}/ *** copy the entire folder content * @ param oldPath String original file path, for example, c:/fqf * @ param newPath String. The copied path is f: /fqf/ff */public void copyFolder (String oldPath, String newPath) {try {(new File (newPath )). mk Dirs (); // If the folder does not exist, create a new folder File a = new File (oldPath); String [] file =. 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 ()). toStr Ing (); byte [] B = new byte [1024*5]; int len; while (len = input. read (B ))! =-1) {output. write (B, 0, len);} output. flush (); output. close (); input. close ();} if (temp. isDirectory () {// if it is a sub-Folder copyFolder (oldPath + "/" + file [I], newPath + "/" + file [I]);} System. out. println ("successful folder copy operation");} catch (Exception e) {System. out. println ("An error occurred while copying the entire folder"); e. printStackTrace () ;}/ *** move the file to the 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 the file to the 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, please press [2] Function 2: create a file "); System. out. println ("to use this function, follow [3] Function 3: delete files"); System. out. println ("to use this function, follow [4] function 4: delete folders"); System. out. println ("to use this function, follow [5] function 5: delete all files in the folder"); System. out. println ("to use this function, follow [6] Function 6: Copy files"); System. out. println ("to use this function, follow [7] function 7: Copy all contents of the folder"); System. out. println ("to use this function, follow [8] function 8: Move files to a 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 follow [10] exit the program"); while (! Exitnow) {FileOperate fo = new FileOperate (); try {BufferedReader Bin = new BufferedReader (new InputStreamReader (System. in); String a = Bin. readLine (); int B = Integer. parseInt (a); switch (B) {case 1: System. out. println ("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 ("you have selected 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 ("incorrect input. enter the number between 1-10 ");} System. out. println ("Please reselect feature");} catch (Exception e) {System. out. println ("incorrect input character or program error ");}}}}

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.