This tool class permanent maintenance, permanent update, if you find that there are bugs or unreasonable, welcome to correct, Bo will correct the first time.
The following are the main contents, the main functions of this class are:
1. create file function;
2. Write an array of bytes to the file;
3. Write a string to the file;
4. Read the byte array from the file;
5. Read the string from the file;
Import java.io.file;import java.io.fileinputstream;import java.io.fileoutputstream;/** * File read/write tool class * * @author Bear * */pub Lic class Fileutil {/** * If the file does not exist, create the file * * @param path file paths * @return */public static string createifnotexist (String Pat h) {File File = new file (path), if (!file.exists ()) {try {file.createnewfile ();} catch (Exception e) {System.out.println (E. GetMessage ());}} return path;} /** * Write data to a file * * @param filePath * Destination file full path * @param data * @return 0 indicates a successful write, 1 indicates no file found, 2 indicates I O exception */public static Boolean writebytes (String FilePath, byte[] data) {try {fileoutputstream fos = new FileOutputStream (fil Epath); fos.write (data); Fos.close (); return true;} catch (Exception e) {System.out.println (E.getmessage ());} return false;} /** * reading data from a file * * * @param @return */public static byte[] readbytes (String file) {try {FileInputStream FIS = new Fi Leinputstream (file); int len = fis.available (); byte[] buffer = new Byte[len];fis.read (buffer); Fis.close (); return buffer ;} catch (Exception e) {System.out.println (E.getmessage ());} return null;} /** * Writing strings to a file string type contents * * @param file path * @param content * File contents * @param charset * Character set used when 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 a file, the return type is String type * * @param file * File path * @param charset * Character set used when reading files, such as Utf-8, GBK, etc. * @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;}}
Android file read/write tool class