开发中经常用到的工具类

在开发中,我们经常会用到一些开发工具类,比如网络请求(当然,网络请求有成熟的框架,在一些大的项目中确实有可用之处,但是在小项目中用框架的话就有点“杀鸡用了杀牛刀了”),所以我们会写一些功能少的框架,再比如说在开发中我们会为了开发的简单,代码易修改和易添加,对代码的重构有很大的帮助


1、在mvc / map 这种开发模式中,model层也就是数据层,一般小的项目中,在android中不会有数据库在前端出现,这时我们为了将数据层归纳的详细,一般会将要使用到的需要保存在sharedpreferences等,和数据层联系起来,比如:在res/values 下建立config.xml文件 将要保存的字段写在里面

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="client_login_sessionToken">client_login_sessionToken</string><!--存储token值-->

</resources>

然后在自己的工具类中 创建字段 并且创建读取该文件的方法

public static final String CLIENT_LOGIN_SESSIONTOKEN = "client_login_sessionToken";

/**
 * 读取配置文件
 * @param name
 * @return
 */
public static String getConfigString(String name){
    int config = mContext.getResources().getIdentifier(name, "config", "com.kerust.client");
    return mContext.getResources().getString(config);
}


在加上写的保存sharedpreferences的工具类

public static void put(Context context, String key, Object object) {

   SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
         Context.MODE_PRIVATE);
   SharedPreferences.Editor editor = sp.edit();

   if (object instanceof String)
   {
      editor.putString(key, (String) object);
   } else if (object instanceof Integer)
   {
      editor.putInt(key, (Integer) object);
   } else if (object instanceof Boolean)
   {
      editor.putBoolean(key, (Boolean) object);
   } else if (object instanceof Float)
   {
      editor.putFloat(key, (Float) object);
   } else if (object instanceof Long)
   {
      editor.putLong(key, (Long) object);
   } else
   {
      editor.putString(key, object.toString());
   }

   SharedPreferencesCompat.apply(editor);
}

在要使用的地方

SPUtils.put(mContext, SettingsInfo.getConfigString( //将token保存到本地
        SettingsInfo.CLIENT_LOGIN_SESSIONTOKEN),sessionToken);

这样将自己要保存的数据保存起来

好了,这只是我自己在开发的过程中的自己的编程习惯

接下来说几个会经常用得到的工具类

1、保存sharedpreferences的工具类

/**
 * 保存在手机里面的文件名
 */
public static final String FILE_NAME = "Launcher_client_share_data";

/**
 * 保存数据的方法,
我们需要拿到保存数据的具体类型,
然后根据类型调用不同的保存方法
 * 
 * @param context
 * @param key
 * @param object
 */
public static void put(Context context, String key, Object object) {

   SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
         Context.MODE_PRIVATE);
   SharedPreferences.Editor editor = sp.edit();

   if (object instanceof String)
   {
      editor.putString(key, (String) object);
   } else if (object instanceof Integer)
   {
      editor.putInt(key, (Integer) object);
   } else if (object instanceof Boolean)
   {
      editor.putBoolean(key, (Boolean) object);
   } else if (object instanceof Float)
   {
      editor.putFloat(key, (Float) object);
   } else if (object instanceof Long)
   {
      editor.putLong(key, (Long) object);
   } else
   {
      editor.putString(key, object.toString());
   }

   SharedPreferencesCompat.apply(editor);
}

/**
 * 得到保存数据的方法,
我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值

 * @param context
 * @param key
 * @param defaultObject
 * @return
 */
public static Object get(Context context, String key, Object defaultObject)
{
   SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
         Context.MODE_PRIVATE);

   if (defaultObject instanceof String)
   {
      return sp.getString(key, (String) defaultObject);
   } else if (defaultObject instanceof Integer)
   {
      return sp.getInt(key, (Integer) defaultObject);
   } else if (defaultObject instanceof Boolean)
   {
      return sp.getBoolean(key, (Boolean) defaultObject);
   } else if (defaultObject instanceof Float)
   {
      return sp.getFloat(key, (Float) defaultObject);
   } else if (defaultObject instanceof Long)
   {
      return sp.getLong(key, (Long) defaultObject);
   }

   return null;

只是常用的保存和取值

2、加密算法

/**
 * DES算法,加密
 *
 * @param data 待加密字符串
 * @param key  需要加密的业务类型
 * @return 加密后的字节数组,一般结合Base64编码使用
 * @throws Exception
 */
public static String encode(String key, String data) {
    if (data == null)
        return null;
    try {
        String value = SettingInfo.getDESValue(key);
        DESKeySpec dks = new DESKeySpec(value.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // key的长度不能够小于8位字节
        Key secretKey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
        IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
        AlgorithmParameterSpec paramSpec = iv;
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
        byte[] bytes = cipher.doFinal(data.getBytes());
        return byte2String(bytes);
    } catch (Exception e) {
        e.printStackTrace();
        return data;
    }
}

/**
 * DES算法,解密
 *
 * @param data 待解密字符串
 * @param key  需要解密的业务类型
 * @return 解密后的字节数组
 * @throws Exception 异常
 */
public static String decode(String key, String data) {
    if (data == null)
        return null;
    try {
        String value = SettingInfo.getDESValue(key);
        DESKeySpec dks = new DESKeySpec(value.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // key的长度不能够小于8位字节
        Key secretKey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
        IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
        AlgorithmParameterSpec paramSpec = iv;
        cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
        return new String(cipher.doFinal(byte2hex(data.getBytes())));
    } catch (Exception e) {
        e.printStackTrace();
        return data;
    }
}

/**
 * 二行制转字符串
 *
 * @param b
 * @return String
 */
private static String byte2String(byte[] b) {
    StringBuilder hs = new StringBuilder();
    String stmp;
    for (int n = 0; b != null && n < b.length; n++) {
        stmp = Integer.toHexString(b[n] & 0XFF);
        if (stmp.length() == 1)
            hs.append('0');
        hs.append(stmp);
    }
    return hs.toString().toUpperCase(Locale.CHINA);
}

/**
 * 二进制转化成16进制
 *
 * @param b
 * @return byte
 */
private static byte[] byte2hex(byte[] b) {
    if ((b.length % 2) != 0)
        throw new IllegalArgumentException();
    byte[] b2 = new byte[b.length / 2];
    for (int n = 0; n < b.length; n += 2) {
        String item = new String(b, n, 2);
        b2[n / 2] = (byte) Integer.parseInt(item, 16);
    }
    return b2;
}

/**
 * md5文件加密的方式
 *
 * @param file
 * @return md5加密的返回加密后的值
 * @throws IOException
 */
public static String md5(File file) throws IOException {
    MessageDigest messagedigest = null;
    FileInputStream in = null;
    FileChannel ch = null;
    byte[] encodeBytes = null;
    try {
        messagedigest = MessageDigest.getInstance("MD5");
        in = new FileInputStream(file);
        ch = in.getChannel();
        MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
        messagedigest.update(byteBuffer);
        encodeBytes = messagedigest.digest();
    } catch (NoSuchAlgorithmException neverHappened) {
        throw new RuntimeException(neverHappened);
    } finally {
        closeQuietly(in);
        closeQuietly(ch);
    }

    return toHexString(encodeBytes);
}

/**
 * MD5 字符串的加密方式
 *
 * @param string
 * @return 加密后的字符串
 */
public static String md5(String string) {
    byte[] encodeBytes = null;
    try {
        encodeBytes = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
    } catch (NoSuchAlgorithmException neverHappened) {
        throw new RuntimeException(neverHappened);
    } catch (UnsupportedEncodingException neverHappened) {
        throw new RuntimeException(neverHappened);
    }

    return toHexString(encodeBytes);
}

public static void closeQuietly(Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (Throwable ignored) {
            Log.d(ignored.getMessage(), ignored + "");
        }
    }
}

private static final char hexDigits[] =
        {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

public static String toHexString(byte[] bytes) {
    if (bytes == null) return "";
    StringBuilder hex = new StringBuilder(bytes.length * 2);
    for (byte b : bytes) {
        hex.append(hexDigits[(b >> 4) & 0x0F]);
        hex.append(hexDigits[b & 0x0F]);
    }
    return hex.toString();
}

3、SD卡保存

/**
 * 判断SDCard是否可用
 *
 * @return
 */
public static boolean isSDCardEnable()
{
   return Environment.getExternalStorageState().equals(
         Environment.MEDIA_MOUNTED);


}


/**
 * 获取SD卡路径
 *
 * @return
 */
public static String getSDCardPath()
{
   return Environment.getExternalStorageDirectory().getAbsolutePath()
         + File.separator;
}


/**
 * 获取SD卡的剩余容量 单位byte
 *
 * @return
 */
public static long getSDCardAllSize()
{
   if (isSDCardEnable())
   {
      StatFs stat = new StatFs(getSDCardPath());
      // 获取空闲的数据块的数量
      long availableBlocks = (long) stat.getAvailableBlocks() - 4;
      // 获取单个数据块的大小(byte)
      long freeBlocks = stat.getAvailableBlocks();
      return freeBlocks * availableBlocks;
   }
   return 0;
}


/**
 * 获取指定路径所在空间的剩余可用容量字节数,单位byte
 *
 * @param filePath
 * @return 容量字节 SDCard可用空间,内部存储可用空间
 */
public static long getFreeBytes(String filePath)
{
   // 如果是sd卡的下的路径,则获取sd卡可用容量
   if (filePath.startsWith(getSDCardPath()))
   {
      filePath = getSDCardPath();
   } else
   {// 如果是内部存储的路径,则获取内存存储的可用容量
      filePath = Environment.getDataDirectory().getAbsolutePath();
   }
   StatFs stat = new StatFs(filePath);
   long availableBlocks = (long) stat.getAvailableBlocks() - 4;
   return stat.getBlockSize() * availableBlocks;
}


/**
 * 获取系统存储路径
 *
 * @return
 */
public static String getRootDirectoryPath()
{
   return Environment.getRootDirectory().getAbsolutePath();
}
4、File操作类

/**
 * read file
 *
 * @param filePath
 * @return if file not exist, return null, else return content of file
 * @throws RuntimeException if an error occurs while operator BufferedReader
 */
public static String readFile(String filePath) {
    String fileContent = "";
    File file = new File(filePath);
    if (!file.isFile()) {
        return null;
    }

    BufferedReader reader = null;
    try {
        InputStreamReader is = new InputStreamReader(new FileInputStream(file));
        reader = new BufferedReader(is);
        String line;
        while ((line = reader.readLine()) != null) {
            fileContent += line + " ";
        }
        reader.close();
        return fileContent;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return fileContent;
}

/**
 * write file
 *
 * @param filePath
 * @param content
 * @param append   is append, if true, write to the end of file, else clear content of file and write into it
 * @return return false if content is empty, true otherwise
 * @throws RuntimeException if an error occurs while operator FileWriter
 */
public static boolean writeFile(String filePath, String content, boolean append) {
    if (filePath == null || filePath.length() == 0) {
        return false;
    }

    FileWriter fileWriter = null;
    try {
        makeDirs(filePath);
        fileWriter = new FileWriter(filePath, append);
        fileWriter.write(content);
        fileWriter.close();
        return true;
    } catch (IOException e) {
        throw new RuntimeException("IOException occurred. ", e);
    } finally {
        if (fileWriter != null) {
            try {
                fileWriter.close();
            } catch (IOException e) {
                throw new RuntimeException("IOException occurred. ", e);
            }
        }
    }
}

/**
 * write file
 *
 * @param filePath
 * @param contentList
 * @param append      is append, if true, write to the end of file, else clear content of file and write into it
 * @return return false if contentList is empty, true otherwise
 * @throws RuntimeException if an error occurs while operator FileWriter
 */
public static boolean writeFile(String filePath, List<String> contentList, boolean append) {
    if (contentList == null || contentList.size() == 0) {
        return false;
    }

    FileWriter fileWriter = null;
    try {
        makeDirs(filePath);
        fileWriter = new FileWriter(filePath, append);
        int i = 0;
        for (String line : contentList) {
            if (i++ > 0) {
                fileWriter.write("\r\n");
            }
            fileWriter.write(line);
        }
        fileWriter.close();
        return true;
    } catch (IOException e) {
        throw new RuntimeException("IOException occurred. ", e);
    } finally {
        if (fileWriter != null) {
            try {
                fileWriter.close();
            } catch (IOException e) {
                throw new RuntimeException("IOException occurred. ", e);
            }
        }
    }
}

/**
 * write file, the string will be written to the begin of the file
 *
 * @param filePath
 * @param content
 * @return
 */
public static boolean writeFile(String filePath, String content) {
    return writeFile(filePath, content, false);
}

/**
 * write file, the string list will be written to the begin of the file
 *
 * @param filePath
 * @param contentList
 * @return
 */
public static boolean writeFile(String filePath, List<String> contentList) {
    return writeFile(filePath, contentList, false);
}

/**
 * write file, the bytes will be written to the begin of the file
 *
 * @param filePath
 * @param stream
 * @return
 * @see {@link #writeFile(String, InputStream, boolean)}
 */
public static boolean writeFile(String filePath, InputStream stream) {
    return writeFile(filePath, stream, false);
}

/**
 * write file
 *
 * @param stream the input stream
 * @param append if <code>true</code>, then bytes will be written to the end of the file rather than the beginning
 * @return return true
 * @throws RuntimeException if an error occurs while operator FileOutputStream
 */
public static boolean writeFile(String filePath, InputStream stream, boolean append) {
    return writeFile(filePath != null ? new File(filePath) : null, stream, append);
}

/**
 * write file, the bytes will be written to the begin of the file
 *
 * @param file
 * @param stream
 * @return
 * @see {@link #writeFile(File, InputStream, boolean)}
 */
public static boolean writeFile(File file, InputStream stream) {
    return writeFile(file, stream, false);
}

/**
 * write file
 *
 * @param file   the file to be opened for writing.
 * @param stream the input stream
 * @param append if <code>true</code>, then bytes will be written to the end of the file rather than the beginning
 * @return return true
 * @throws RuntimeException if an error occurs while operator FileOutputStream
 */
public static boolean writeFile(File file, InputStream stream, boolean append) {
    OutputStream o = null;
    try {
        makeDirs(file.getAbsolutePath());
        o = new FileOutputStream(file, append);
        byte data[] = new byte[1024];
        int length = -1;
        while ((length = stream.read(data)) != -1) {
            o.write(data, 0, length);
        }
        o.flush();
        return true;
    } catch (FileNotFoundException e) {
        throw new RuntimeException("FileNotFoundException occurred. ", e);
    } catch (IOException e) {
        throw new RuntimeException("IOException occurred. ", e);
    } finally {
        if (o != null) {
            try {
                o.close();
                stream.close();
            } catch (IOException e) {
                throw new RuntimeException("IOException occurred. ", e);
            }
        }
    }
}

/**
 * move file
 *
 * @param sourceFilePath
 * @param destFilePath
 */
public static void moveFile(String sourceFilePath, String destFilePath) {
    if (TextUtils.isEmpty(sourceFilePath) || TextUtils.isEmpty(destFilePath)) {
        throw new RuntimeException("Both sourceFilePath and destFilePath cannot be null.");
    }
    moveFile(new File(sourceFilePath), new File(destFilePath));
}

/**
 * move file
 *
 * @param srcFile
 * @param destFile
 */
public static void moveFile(File srcFile, File destFile) {
    boolean rename = srcFile.renameTo(destFile);
    if (!rename) {
        copyFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath());
        deleteFile(srcFile.getAbsolutePath());
    }
}

/**
 * copy file
 *
 * @param sourceFilePath
 * @param destFilePath
 * @return
 * @throws RuntimeException if an error occurs while operator FileOutputStream
 */
public static boolean copyFile(String sourceFilePath, String destFilePath) {
    InputStream inputStream = null;
    try {
        inputStream = new FileInputStream(sourceFilePath);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("FileNotFoundException occurred. ", e);
    }
    return writeFile(destFilePath, inputStream);
}

/**
 * read file to string list, a element of list is a line
 *
 * @param filePath
 * @param charsetName The name of a supported {@link java.nio.charset.Charset </code>charset<code>}
 * @return if file not exist, return null, else return content of file
 * @throws RuntimeException if an error occurs while operator BufferedReader
 */
public static List<String> readFileToList(String filePath, String charsetName) {
    File file = new File(filePath);
    List<String> fileContent = new ArrayList<String>();
    if (file == null || !file.isFile()) {
        return null;
    }

    BufferedReader reader = null;
    try {
        InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
        reader = new BufferedReader(is);
        String line = null;
        while ((line = reader.readLine()) != null) {
            fileContent.add(line);
        }
        reader.close();
        return fileContent;
    } catch (IOException e) {
        throw new RuntimeException("IOException occurred. ", e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                throw new RuntimeException("IOException occurred. ", e);
            }
        }
    }
}

/**
 * get file name from path, not include suffix
 * <p/>
 * getFileNameWithoutExtension(null)               =   null
 * getFileNameWithoutExtension("")                 =   ""
 * getFileNameWithoutExtension("   ")              =   "   "
 * getFileNameWithoutExtension("abc")              =   "abc"
 * getFileNameWithoutExtension("a.mp3")            =   "a"
 * getFileNameWithoutExtension("a.b.rmvb")         =   "a.b"
 * getFileNameWithoutExtension("c:\\")              =   ""
 * getFileNameWithoutExtension("c:\\a")             =   "a"
 * getFileNameWithoutExtension("c:\\a.b")           =   "a"
 * getFileNameWithoutExtension("c:a.txt\\a")        =   "a"
 * getFileNameWithoutExtension("/home/admin")      =   "admin"
 * getFileNameWithoutExtension("/home/admin/a.txt/b.mp3")  =   "b"
 *
 * @param filePath
 * @return file name from path, not include suffix
 * @see
 */
public static String getFileNameWithoutExtension(String filePath) {
    if (filePath == null || filePath.length() == 0) {
        return filePath;
    }

    int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
    int filePosi = filePath.lastIndexOf(File.separator);
    if (filePosi == -1) {
        return (extenPosi == -1 ? filePath : filePath.substring(0, extenPosi));
    }
    if (extenPosi == -1) {
        return filePath.substring(filePosi + 1);
    }
    return (filePosi < extenPosi ? filePath.substring(filePosi + 1, extenPosi) : filePath.substring(filePosi + 1));
}

/**
 * get file name from path, include suffix
 * <p/>
 * getFileName(null)               =   null
 * getFileName("")                 =   ""
 * getFileName("   ")              =   "   "
 * getFileName("a.mp3")            =   "a.mp3"
 * getFileName("a.b.rmvb")         =   "a.b.rmvb"
 * getFileName("abc")              =   "abc"
 * getFileName("c:\\")              =   ""
 * getFileName("c:\\a")             =   "a"
 * getFileName("c:\\a.b")           =   "a.b"
 * getFileName("c:a.txt\\a")        =   "a"
 * getFileName("/home/admin")      =   "admin"
 * getFileName("/home/admin/a.txt/b.mp3")  =   "b.mp3"
 *
 * @param filePath
 * @return file name from path, include suffix
 */
public static String getFileName(String filePath) {
    if (filePath == null || filePath.length() == 0) {
        return filePath;
    }

    int filePosi = filePath.lastIndexOf(File.separator);
    return (filePosi == -1) ? filePath : filePath.substring(filePosi + 1);
}

/**
 * get folder name from path
 * <p/>
 * getFolderName(null)               =   null
 * getFolderName("")                 =   ""
 * getFolderName("   ")              =   ""
 * getFolderName("a.mp3")            =   ""
 * getFolderName("a.b.rmvb")         =   ""
 * getFolderName("abc")              =   ""
 * getFolderName("c:\\")              =   "c:"
 * getFolderName("c:\\a")             =   "c:"
 * getFolderName("c:\\a.b")           =   "c:"
 * getFolderName("c:a.txt\\a")        =   "c:a.txt"
 * getFolderName("c:a\\b\\c\\d.txt")    =   "c:a\\b\\c"
 * getFolderName("/home/admin")      =   "/home"
 * getFolderName("/home/admin/a.txt/b.mp3")  =   "/home/admin/a.txt"
 *
 * @param filePath
 * @return
 */
public static String getFolderName(String filePath) {

    if (filePath == null || filePath.length() == 0) {
        return filePath;
    }

    int filePosi = filePath.lastIndexOf(File.separator);
    return (filePosi == -1) ? "" : filePath.substring(0, filePosi);
}

/**
 * get suffix of file from path
 * <p/>
 * getFileExtension(null)               =   ""
 * getFileExtension("")                 =   ""
 * getFileExtension("   ")              =   "   "
 * getFileExtension("a.mp3")            =   "mp3"
 * getFileExtension("a.b.rmvb")         =   "rmvb"
 * getFileExtension("abc")              =   ""
 * getFileExtension("c:\\")              =   ""
 * getFileExtension("c:\\a")             =   ""
 * getFileExtension("c:\\a.b")           =   "b"
 * getFileExtension("c:a.txt\\a")        =   ""
 * getFileExtension("/home/admin")      =   ""
 * getFileExtension("/home/admin/a.txt/b")  =   ""
 * getFileExtension("/home/admin/a.txt/b.mp3")  =   "mp3"
 *
 * @param filePath
 * @return
 */
public static String getFileExtension(String filePath) {
    if (filePath == null || filePath.trim().length() == 0) {
        return filePath;
    }

    int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
    int filePosi = filePath.lastIndexOf(File.separator);
    if (extenPosi == -1) {
        return "";
    }
    return (filePosi >= extenPosi) ? "" : filePath.substring(extenPosi + 1);
}

/**
 * Creates the directory named by the trailing filename of this file, including the complete directory path required
 * to create this directory.
 * Attentions:
 * makeDirs("C:\\Users\\Trinea") can only create users folder
 * makeFolder("C:\\Users\\Trinea\\") can create Trinea folder
 *
 * @param filePath
 * @return true if the necessary directories have been created or the target directory already exists, false one of
 * the directories can not be created.
 * if {@link FileUtils#getFolderName(String)} return null, return false
 * if target directory already exists, return true
 * return {@link File#makeFolder}
 */
public static boolean makeDirs(String filePath) {
    String folderName = getFolderName(filePath);
    if (filePath == null || filePath.length() == 0) {
        return false;
    }

    File folder = new File(folderName);
    return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
}

/**
 * @param filePath
 * @return
 * @see #makeDirs(String)
 */
public static boolean makeFolders(String filePath) {
    return makeDirs(filePath);
}

/**
 * Indicates if this file represents a file on the underlying file system.
 *
 * @param filePath
 * @return
 */
public static boolean isFileExist(String filePath) {
    if (filePath == null || filePath.trim().length() == 0) {
        return false;
    }

    File file = new File(filePath);
    return (file.exists() && file.isFile());
}

/**
 * Indicates if this file represents a directory on the underlying file system.
 *
 * @param directoryPath
 * @return
 */
public static boolean isFolderExist(String directoryPath) {
    if (directoryPath == null || directoryPath.trim().length() == 0) {
        return false;
    }

    File dire = new File(directoryPath);
    return (dire.exists() && dire.isDirectory());
}

/**
 * delete file or directory
 *
 * if path is null or empty, return tru
 * if path not exist, return true
 * if path exist, delete recursion. return true
 *
 * @param path
 * @return
 */
public static boolean deleteFile(String path) {
    if (path == null || path.trim().length() == 0) {
        return true;
    }

    File file = new File(path);
    if (!file.exists()) {
        return true;
    }
    if (file.isFile()) {
        return file.delete();
    }
    if (!file.isDirectory()) {
        return false;
    }
    for (File f : file.listFiles()) {
        if (f.isFile()) {
            f.delete();
        } else if (f.isDirectory()) {
            deleteFile(f.getAbsolutePath());
        }
    }
    return file.delete();
}

/**
 * get file size
 * if path is null or empty, return -1
 * <if path exist and it is a file, return file size, else return -1
 *
 * @param path
 * @return returns the length of this file in bytes. returns -1 if the file does not exist.
 */
public static long getFileSize(String path) {
    if (path == null || path.trim().length() == 0) {
        return -1;
    }

    File file = new File(path);
    return (file.exists() && file.isFile() ? file.length() : -1);
}
5、字符串转换

/**
 * 指令字符里很多字符是终结符: \r ,在输出日志的无法打印,为了日志能看到,处理掉这个字符
 *
 * @param bytes 字节
 * @return 字符串
 */
public static String transferForPrint(byte... bytes) {
    if (bytes == null)
        return null;
    return transferForPrint(new String(bytes));
}

/**
 * @param str 字符串
 * @return 字符串
 */
public static String transferForPrint(String str) {
    if (TextUtils.isEmpty(str))
        return str;
    str = str.replace('\r', ' ');
    str = str.replace('\n', ' ');
    if (str.endsWith(">")) {
        str = str.substring(0, str.length() - 1);
    }
    return str;
}

/**
 * 转换成 16进制字符串
 *
 * @param b 字节
 * @return 字符串
 */
private static String toHexStr(byte b) {
    String str = Integer.toHexString(0xFF & b);
    if (str.length() == 1)
        str = "0" + str;
    return str.toUpperCase();
}

/**
 * 转换成 16进制字符串
 *
 * @param bytes 字节
 * @return 字符串
 */
public static String toHexString(byte... bytes) {
    if (bytes == null)
        return null;
    StringBuilder sb = new StringBuilder();
    if (bytes.length < 20) {
        sb.append("[");
        for (int i = 0; i < bytes.length; i++) {
            sb.append(toHexStr(bytes[i])).append(",");
        }
        sb.append("]");
    } else {
        sb.append("[");
        for (int i = 0; i < 4; i++) {
            sb.append(toHexStr(bytes[i])).append(",");
        }
        sb.append("...");
        for (int i = bytes.length - 5; i < bytes.length; i++) {
            sb.append(toHexStr(bytes[i])).append(",");
        }
        sb.setLength(sb.length() - 1);
        sb.append("]");
    }
    return sb.toString();
}
6、字体操作

//将钥匙使用的字体的类型
public static Typeface TEXT_TYPE ;
private static Context mContext;
// 定义一个私有的构造方法
private FrontUtils() {
}
// 将自身的实例对象设置为一个属性,并加上Static和final修饰符
private static final FrontUtils fontUtils = new FrontUtils();

// 静态方法返回该类的实例
public static FrontUtils getInstance(Context mContext) {
    return fontUtils;
}

public FrontUtils(Context mContext) {
    this.mContext = mContext;
}

/**
 * 获取应用中将要用到的字体
 * 从assets中获取字体资源
 * @return
 */
public static Typeface getFont(){
    try{
        TEXT_TYPE = Typeface.createFromAsset(mContext.getAssets(),"fronts/NotoSansHans-Black.otf");
    }catch(Exception e){
        TEXT_TYPE = Typeface.DEFAULT;
    }
    return TEXT_TYPE;
}
这些都是在开发中基本会用的到工具类 ,在这里给自己做个笔记,如果和哪位大哥的相同,还望包涵,也在此谢谢您
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值