File read/write tools for Android and android
This tool is permanently maintained and updated. If you find any bug or unreasonable, you are welcome to correct it as soon as possible.
The main functions of this class are as follows:
1. File Creation;
2. Write a byte array to the file;
3. Write a string to the file;
4. Read the byte array from the file;
5. Read strings from files;
Import java. io. file; import java. io. fileInputStream; import java. io. fileOutputStream;/*** file read/write tool class ** @ author bear **/public class FileUtil {/*** if the file does not exist, create the File ** @ param path * @ return */public static String createIfNotExist (String path) {file File = new File (path); if (! File. exists () {try {file. createNewFile ();} catch (Exception e) {System. out. println (e. getMessage () ;}} return path ;} /*** write data to the file ** @ param filePath * full path to the target file * @ param data * data to be written * @ return true indicates successful write; false indicates failed write * /public static boolean writeBytes (String filePath, byte [] data) {try {FileOutputStream fos = new FileOutputStream (filePath); fos. write (data); fos. close (); return true;} catch (Exception e) {System. out. println (e. getMessage ();} return false;}/*** read data from the file ** @ param file * @ return */public static byte [] readBytes (String file) {try {FileInputStream fiis = new FileInputStream (file); int len = fiis. available (); byte [] buffer = new byte [len]; FCM. read (buffer); FCM. close (); return buffer;} catch (Exception e) {System. out. println (e. getMessage ();} return null ;} /*** write String-type content to the file ** @ param file * file path * @ param content * file content * @ param charset * character set used for writing * /public static void writeString (String file, string content, String charset) {try {byte [] data = content. getBytes (charset); writeBytes (file, data);} catch (Exception e) {System. out. println (e. getMessage () ;}}/*** read data from the file, the return type is String type ** @ param file * file path * @ param charset * the character set used to read the file, for example, UTF-8 and GBK * @ return */public static String readString (String file, String charset) {byte [] data = readBytes (file); String ret = null; try {ret = new String (data, charset);} catch (Exception e) {System. out. println (e. getMessage () ;}return ret ;}}