Android 框架:快速开发中Util常用工具类总结

/**

  • get int preferences

  • @param context

  • @param key The name of the preference to retrieve

  • @param defaultValue Value to return if this preference does not exist

  • @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with

  •     this name that is not a int
    

*/

public static int getInt(Context context, String key, int defaultValue) {

SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);

return settings.getInt(key, defaultValue);

}

/**

  • put long preferences

  • @param context

  • @param key The name of the preference to modify

  • @param value The new value for the preference

  • @return True if the new values were successfully written to persistent storage.

*/

public static boolean putLong(Context context, String key, long value) {

SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);

SharedPreferences.Editor editor = settings.edit();

editor.putLong(key, value);

return editor.commit();

}

/**

  • get long preferences

  • @param context

  • @param key The name of the preference to retrieve

  • @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this

  •     name that is not a long
    
  • @see #getLong(Context, String, long)

*/

public static long getLong(Context context, String key) {

return getLong(context, key, -1);

}

/**

  • get long preferences

  • @param context

  • @param key The name of the preference to retrieve

  • @param defaultValue Value to return if this preference does not exist

  • @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with

  •     this name that is not a long
    

*/

public static long getLong(Context context, String key, long defaultValue) {

SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);

return settings.getLong(key, defaultValue);

}

/**

  • put float preferences

  • @param context

  • @param key The name of the preference to modify

  • @param value The new value for the preference

  • @return True if the new values were successfully written to persistent storage.

*/

public static boolean putFloat(Context context, String key, float value) {

SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);

SharedPreferences.Editor editor = settings.edit();

editor.putFloat(key, value);

return editor.commit();

}

/**

  • get float preferences

  • @param context

  • @param key The name of the preference to retrieve

  • @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this

  •     name that is not a float
    
  • @see #getFloat(Context, String, float)

*/

public static float getFloat(Context context, String key) {

return getFloat(context, key, -1);

}

/**

  • get float preferences

  • @param context

  • @param key The name of the preference to retrieve

  • @param defaultValue Value to return if this preference does not exist

  • @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with

  •     this name that is not a float
    

*/

public static float getFloat(Context context, String key, float defaultValue) {

SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);

return settings.getFloat(key, defaultValue);

}

/**

  • put boolean preferences

  • @param context

  • @param key The name of the preference to modify

  • @param value The new value for the preference

  • @return True if the new values were successfully written to persistent storage.

*/

public static boolean putBoolean(Context context, String key, boolean value) {

SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);

SharedPreferences.Editor editor = settings.edit();

editor.putBoolean(key, value);

return editor.commit();

}

/**

  • get boolean preferences, default is false

  • @param context

  • @param key The name of the preference to retrieve

  • @return The preference value if it exists, or false. Throws ClassCastException if there is a preference with this

  •     name that is not a boolean
    
  • @see #getBoolean(Context, String, boolean)

*/

public static boolean getBoolean(Context context, String key) {

return getBoolean(context, key, false);

}

/**

  • get boolean preferences

  • @param context

  • @param key The name of the preference to retrieve

  • @param defaultValue Value to return if this preference does not exist

  • @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with

  •     this name that is not a boolean
    

*/

public static boolean getBoolean(Context context, String key, boolean defaultValue) {

SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);

return settings.getBoolean(key, defaultValue);

}

}

四、单位转换类 DensityUtils.java

public class DensityUtils

{

private DensityUtils()

{

/* cannot be instantiated */

throw new UnsupportedOperationException(“cannot be instantiated”);

}

/**

  • dp转px

  • @param context

  • @param val

  • @return

*/

public static int dp2px(Context context, float dpVal)

{

return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,

dpVal, context.getResources().getDisplayMetrics());

}

/**

  • sp转px

  • @param context

  • @param val

  • @return

*/

public static int sp2px(Context context, float spVal)

{

return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,

spVal, context.getResources().getDisplayMetrics());

}

/**

  • px转dp

  • @param context

  • @param pxVal

  • @return

*/

public static float px2dp(Context context, float pxVal)

{

final float scale = context.getResources().getDisplayMetrics().density;

return (pxVal / scale);

}

/**

  • px转sp

  • @param fontScale

  • @param pxVal

  • @return

*/

public static float px2sp(Context context, float pxVal)

{

return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);

}

}

  • TypedValue

Container for a dynamically typed data value. Primarily used with Resources for holding resource values.

  • applyDimension(int unit, float value, DisplayMetrics metrics)

Converts an unpacked complex data value holding a dimension to its final floating point value.

五、SD卡相关辅助类 SDCardUtils.java

public class SDCardUtils

{

private SDCardUtils()

{

/* cannot be instantiated */

throw new UnsupportedOperationException(“cannot be instantiated”);

}

/**

  • 判断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();

}

}

  • StatFs 是Android提供的一个类:

Retrieve overall information about the space on a filesystem. This is a wrapper for Unix statvfs().

检索一个文件系统的整体信息空间。这是一个Unix statvfs() 包装器。

六、屏幕相关辅助类 ScreenUtils.java

public class ScreenUtils

{

private ScreenUtils()

{

/* cannot be instantiated */

throw new UnsupportedOperationException(“cannot be instantiated”);

}

/**

  • 获得屏幕高度

  • @param context

  • @return

*/

public static int getScreenWidth(Context context)

{

WindowManager wm = (WindowManager) context

.getSystemService(Context.WINDOW_SERVICE);

DisplayMetrics outMetrics = new DisplayMetrics();

wm.getDefaultDisplay().getMetrics(outMetrics);

return outMetrics.widthPixels;

}

/**

  • 获得屏幕宽度

  • @param context

  • @return

*/

public static int getScreenHeight(Context context)

{

WindowManager wm = (WindowManager) context

.getSystemService(Context.WINDOW_SERVICE);

DisplayMetrics outMetrics = new DisplayMetrics();

wm.getDefaultDisplay().getMetrics(outMetrics);

return outMetrics.heightPixels;

}

/**

  • 获得状态栏的高度

  • @param context

  • @return

*/

public static int getStatusHeight(Context context)

{

int statusHeight = -1;

try

{

Class<?> clazz = Class.forName(“com.android.internal.R$dimen”);

Object object = clazz.newInstance();

int height = Integer.parseInt(clazz.getField(“status_bar_height”)

.get(object).toString());

statusHeight = context.getResources().getDimensionPixelSize(height);

} catch (Exception e)

{

e.printStackTrace();

}

return statusHeight;

}

/**

  • 获取当前屏幕截图,包含状态栏

  • @param activity

  • @return

*/

public static Bitmap snapShotWithStatusBar(Activity activity)

{

View view = activity.getWindow().getDecorView();

view.setDrawingCacheEnabled(true);

view.buildDrawingCache();

Bitmap bmp = view.getDrawingCache();

int width = getScreenWidth(activity);

int height = getScreenHeight(activity);

Bitmap bp = null;

bp = Bitmap.createBitmap(bmp, 0, 0, width, height);

view.destroyDrawingCache();

return bp;

}

/**

  • 获取当前屏幕截图,不包含状态栏

  • @param activity

  • @return

*/

public static Bitmap snapShotWithoutStatusBar(Activity activity)

{

View view = activity.getWindow().getDecorView();

view.setDrawingCacheEnabled(true);

view.buildDrawingCache();

Bitmap bmp = view.getDrawingCache();

Rect frame = new Rect();

activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);

int statusBarHeight = frame.top;

int width = getScreenWidth(activity);

int height = getScreenHeight(activity);

Bitmap bp = null;

bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height

  • statusBarHeight);

view.destroyDrawingCache();

return bp;

}

}

七、App相关辅助类 APPUtils.java

public class AppUtils

{

private AppUtils()

{

/* cannot be instantiated */

throw new UnsupportedOperationException(“cannot be instantiated”);

}

/**

  • 获取应用程序名称

*/

public static String getAppName(Context context)

{

try

{

PackageManager packageManager = context.getPackageManager();

PackageInfo packageInfo = packageManager.getPackageInfo(

context.getPackageName(), 0);

int labelRes = packageInfo.applicationInfo.labelRes;

return context.getResources().getString(labelRes);

} catch (NameNotFoundException e)

{

e.printStackTrace();

}

return null;

}

/**

  • [获取应用程序版本名称信息]

  • @param context

  • @return 当前应用的版本名称

*/

public static String getVersionName(Context context)

{

try

{

PackageManager packageManager = context.getPackageManager();

PackageInfo packageInfo = packageManager.getPackageInfo(

context.getPackageName(), 0);

return packageInfo.versionName;

} catch (NameNotFoundException e)

{

e.printStackTrace();

}

return null;

}

}

八、软键盘相关辅助类KeyBoardUtils.java

/**

  • 打开或关闭软键盘

*/

public class KeyBoardUtils

{

/**

  • 打卡软键盘

  • @param mEditText 输入框

  • @param mContext 上下文

*/

public static void openKeybord(EditText mEditText, Context mContext)

{

InputMethodManager imm = (InputMethodManager) mContext

.getSystemService(Context.INPUT_METHOD_SERVICE);

imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);

imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,

InputMethodManager.HIDE_IMPLICIT_ONLY);

}

/**

  • 关闭软键盘

  • @param mEditText 输入框

  • @param mContext 上下文

*/

public static void closeKeybord(EditText mEditText, Context mContext)

{

InputMethodManager imm = (InputMethodManager) mContext

.getSystemService(Context.INPUT_METHOD_SERVICE);

imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);

}

}

九、网络相关辅助类 NetUtils.java

public class NetUtils

{

private NetUtils()

{

/* cannot be instantiated */

throw new UnsupportedOperationException(“cannot be instantiated”);

}

/**

  • 判断网络是否连接

*/

public static boolean isConnected(Context context)

{

ConnectivityManager connectivity = (ConnectivityManager) context

.getSystemService(Context.CONNECTIVITY_SERVICE);

if (null != connectivity)

{

NetworkInfo info = connectivity.getActiveNetworkInfo();

if (null != info && info.isConnected())

{

if (info.getState() == NetworkInfo.State.CONNECTED)

{

return true;

}

}

}

return false;

}

/**

  • 判断是否是wifi连接

*/

public static boolean isWifi(Context context)

{

ConnectivityManager cm = (ConnectivityManager) context

.getSystemService(Context.CONNECTIVITY_SERVICE);

if (cm == null)

return false;

return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;

}

/**

  • 打开网络设置界面

*/

public static void openSetting(Activity activity)

{

Intent intent = new Intent(“/”);

ComponentName cm = new ComponentName(“com.android.settings”,

“com.android.settings.WirelessSettings”);

intent.setComponent(cm);

intent.setAction(“android.intent.action.VIEW”);

activity.startActivityForResult(intent, 0);

}

}

十、Http相关辅助类 HttpUtils.java

/**

  • Http请求的工具类

*/

public class HttpUtils

{

private static final int TIMEOUT_IN_MILLIONS = 5000;

public interface CallBack

{

void onRequestComplete(String result);

}

/**

  • 异步的Get请求

  • @param urlStr

  • @param callBack

*/

public static void doGetAsyn(final String urlStr, final CallBack callBack)

{

new Thread()

{

public void run()

{

try

{

String result = doGet(urlStr);

if (callBack != null)

{

callBack.onRequestComplete(result);

}

} catch (Exception e)

{

e.printStackTrace();

}

};

}.start();

}

/**

  • 异步的Post请求

  • @param urlStr

  • @param params

  • @param callBack

  • @throws Exception

*/

public static void doPostAsyn(final String urlStr, final String params,

final CallBack callBack) throws Exception

{

new Thread()

{

public void run()

{

try

{

String result = doPost(urlStr, params);

if (callBack != null)

{

callBack.onRequestComplete(result);

}

} catch (Exception e)

{

e.printStackTrace();

}

};

}.start();

}

/**

  • Get请求,获得返回数据

  • @param urlStr

  • @return

  • @throws Exception

*/

public static String doGet(String urlStr)

{

URL url = null;

HttpURLConnection conn = null;

InputStream is = null;

ByteArrayOutputStream baos = null;

try

{

url = new URL(urlStr);

conn = (HttpURLConnection) url.openConnection();

conn.setReadTimeout(TIMEOUT_IN_MILLIONS);

conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);

conn.setRequestMethod(“GET”);

conn.setRequestProperty(“accept”, “/”);

conn.setRequestProperty(“connection”, “Keep-Alive”);

if (conn.getResponseCode() == 200)

{

is = conn.getInputStream();

baos = new ByteArrayOutputStream();

int len = -1;

byte[] buf = new byte[128];

while ((len = is.read(buf)) != -1)

{

baos.write(buf, 0, len);

}

baos.flush();

return baos.toString();

} else

{

throw new RuntimeException(" responseCode is not 200 … ");

}

} catch (Exception e)

{

e.printStackTrace();

} finally

{

try

{

if (is != null)

is.close();

} catch (IOException e)

{

}

try

{

if (baos != null)

baos.close();

} catch (IOException e)

{

}

conn.disconnect();

}

return null ;

}

/**

  • 向指定 URL 发送POST方法的请求

  • @param url

  •        发送请求的 URL  
    
  • @param param

  •        请求参数,请求参数应该是 name1=value1&name2=value2 的形式。  
    
  • @return 所代表远程资源的响应结果

  • @throws Exception

*/

public static String doPost(String url, String param)

{

PrintWriter out = null;

BufferedReader in = null;

String result = “”;

try

{

URL realUrl = new URL(url);

// 打开和URL之间的连接

HttpURLConnection conn = (HttpURLConnection) realUrl

.openConnection();

// 设置通用的请求属性

conn.setRequestProperty(“accept”, “/”);

conn.setRequestProperty(“connection”, “Keep-Alive”);

conn.setRequestMethod(“POST”);

conn.setRequestProperty(“Content-Type”,

“application/x-www-form-urlencoded”);

conn.setRequestProperty(“charset”, “utf-8”);

conn.setUseCaches(false);

// 发送POST请求必须设置如下两行

conn.setDoOutput(true);

conn.setDoInput(true);

conn.setReadTimeout(TIMEOUT_IN_MILLIONS);

conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);

if (param != null && !param.trim().equals(“”))

{

// 获取URLConnection对象对应的输出流

out = new PrintWriter(conn.getOutputStream());

// 发送请求参数

out.print(param);

// flush输出流的缓冲

out.flush();

}

// 定义BufferedReader输入流来读取URL的响应

in = new BufferedReader(

new InputStreamReader(conn.getInputStream()));

String line;

while ((line = in.readLine()) != null)

{

result += line;

}

} catch (Exception e)

{

e.printStackTrace();

}

// 使用finally块来关闭输出流、输入流

finally

{

try

{

if (out != null)

{

out.close();

}

if (in != null)

{

in.close();

}

} catch (IOException ex)

{

ex.printStackTrace();

}

}

return result;

}

}

十一、时间工具类 TimeUtils.java

public class TimeUtils {

public static final SimpleDateFormat DEFAULT_DATE_FORMAT =

new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

public static final SimpleDateFormat DATE_FORMAT_DATE =

new SimpleDateFormat(“yyyy-MM-dd”);

private TimeUtils() {

throw new AssertionError();

}

/**

  • long time to string

  • @param timeInMillis

  • @param dateFormat

  • @return

*/

public static String getTime(long timeInMillis, SimpleDateFormat dateFormat) {

return dateFormat.format(new Date(timeInMillis));

}

/**

  • long time to string, format is {@link #DEFAULT_DATE_FORMAT}

  • @param timeInMillis

  • @return

*/

public static String getTime(long timeInMillis) {

return getTime(timeInMillis, DEFAULT_DATE_FORMAT);

}

/**

  • get current time in milliseconds

  • @return

*/

public static long getCurrentTimeInLong() {

return System.currentTimeMillis();

}

/**

  • get current time in milliseconds, format is {@link #DEFAULT_DATE_FORMAT}

  • @return

*/

public static String getCurrentTimeInString() {

return getTime(getCurrentTimeInLong());

}

/**

  • get current time in milliseconds

  • @return

*/

public static String getCurrentTimeInString(SimpleDateFormat dateFormat) {

return getTime(getCurrentTimeInLong(), dateFormat);

}

}

十二、文件工具类 FileUtils.java

public class FileUtils {

public final static String FILE_EXTENSION_SEPARATOR = “.”;

private FileUtils() {

throw new AssertionError();

}

/**

  • read file

  • @param filePath

  • @param charsetName The name of a supported {@link java.nio.charset.Charset charset}

  • @return if file not exist, return null, else return content of file

  • @throws RuntimeException if an error occurs while operator BufferedReader

*/

public static StringBuilder readFile(String filePath, String charsetName) {

File file = new File(filePath);

StringBuilder fileContent = new StringBuilder(“”);

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) {

if (!fileContent.toString().equals(“”)) {

fileContent.append(“\r\n”);

}

fileContent.append(line);

}

return fileContent;

} catch (IOException e) {

throw new RuntimeException("IOException occurred. ", e);

} finally {

IOUtils.close(reader);

}

}

/**

  • 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 (StringUtils.isEmpty(content)) {

return false;

}

FileWriter fileWriter = null;

try {

makeDirs(filePath);

fileWriter = new FileWriter(filePath, append);

fileWriter.write(content);

return true;

} catch (IOException e) {

throw new RuntimeException("IOException occurred. ", e);

} finally {

IOUtils.close(fileWriter);

}

}

/**

  • 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 contentList, boolean append) {

if (ListUtils.isEmpty(contentList)) {

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);

}

return true;

} catch (IOException e) {

throw new RuntimeException("IOException occurred. ", e);

} finally {

IOUtils.close(fileWriter);

}

}

/**

  • 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 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 file the file to be opened for writing.

  • @param stream the input stream

  • @param append if true, 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 true, 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 {

IOUtils.close(o);

IOUtils.close(stream);

}

}

/**

  • 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 charset}

  • @return if file not exist, return null, else return content of file

  • @throws RuntimeException if an error occurs while operator BufferedReader

*/

public static List readFileToList(String filePath, String charsetName) {

File file = new File(filePath);

List fileContent = new ArrayList();

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);

}

return fileContent;

} catch (IOException e) {

throw new RuntimeException("IOException occurred. ", e);

} finally {

IOUtils.close(reader);

}

}

/**

  • get file name from path, not include suffix

  •  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 (StringUtils.isEmpty(filePath)) {

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

  •  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 (StringUtils.isEmpty(filePath)) {

return filePath;

}

int filePosi = filePath.lastIndexOf(File.separator);

return (filePosi == -1) ? filePath : filePath.substring(filePosi + 1);

}

/**

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加V获取:vip204888 (备注Android)
img

作者2013年从java开发,转做Android开发,在小厂待过,也去过华为,OPPO等大厂待过,18年四月份进了阿里一直到现在。

参与过不少面试,也当面试官 面试过很多人。深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长,不成体系的学习效果低效漫长,而且极易碰到天花板技术停滞不前!

我整理了一份阿里P7级别的最系统的Android开发主流技术,特别适合有3-5年以上经验的小伙伴深入学习提升。

主要包括阿里,以及字节跳动,腾讯,华为,小米,等一线互联网公司主流架构技术。如果你想深入系统学习Android开发,成为一名合格的高级工程师,可以收藏一下这些Android进阶技术选型

我搜集整理过这几年阿里,以及腾讯,字节跳动,华为,小米等公司的面试题,把面试的要求和技术点梳理成一份大而全的“ Android架构师”面试 Xmind(实际上比预期多花了不少精力),包含知识脉络 + 分支细节。

Java语言与原理;
大厂,小厂。Android面试先看你熟不熟悉Java语言

高级UI与自定义view;
自定义view,Android开发的基本功。

性能调优;
数据结构算法,设计模式。都是这里面的关键基础和重点需要熟练的。

NDK开发;
未来的方向,高薪必会。

前沿技术;
组件化,热升级,热修复,框架设计

网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。

我在搭建这些技术框架的时候,还整理了系统的高级进阶教程,会比自己碎片化学习效果强太多,CodeChina上可见;

当然,想要深入学习并掌握这些能力,并不简单。关于如何学习,做程序员这一行什么工作强度大家都懂,但是不管工作多忙,每周也要雷打不动的抽出 2 小时用来学习。

不出半年,你就能看出变化!

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 (StringUtils.isEmpty(filePath)) {

return filePath;

}

int filePosi = filePath.lastIndexOf(File.separator);

return (filePosi == -1) ? filePath : filePath.substring(filePosi + 1);

}

/**

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
[外链图片转存中…(img-E4YBZZUA-1711911131569)]
[外链图片转存中…(img-IAE8ckHL-1711911131569)]
[外链图片转存中…(img-YAGmZRhS-1711911131570)]
[外链图片转存中…(img-j1fBZwkB-1711911131570)]
[外链图片转存中…(img-m6XtS2sH-1711911131571)]
[外链图片转存中…(img-5utu7Juj-1711911131571)]
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加V获取:vip204888 (备注Android)
[外链图片转存中…(img-3qsEzglq-1711911131571)]

作者2013年从java开发,转做Android开发,在小厂待过,也去过华为,OPPO等大厂待过,18年四月份进了阿里一直到现在。

参与过不少面试,也当面试官 面试过很多人。深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长,不成体系的学习效果低效漫长,而且极易碰到天花板技术停滞不前!

我整理了一份阿里P7级别的最系统的Android开发主流技术,特别适合有3-5年以上经验的小伙伴深入学习提升。

主要包括阿里,以及字节跳动,腾讯,华为,小米,等一线互联网公司主流架构技术。如果你想深入系统学习Android开发,成为一名合格的高级工程师,可以收藏一下这些Android进阶技术选型

我搜集整理过这几年阿里,以及腾讯,字节跳动,华为,小米等公司的面试题,把面试的要求和技术点梳理成一份大而全的“ Android架构师”面试 Xmind(实际上比预期多花了不少精力),包含知识脉络 + 分支细节。

[外链图片转存中…(img-xVz7O2N7-1711911131572)]

Java语言与原理;
大厂,小厂。Android面试先看你熟不熟悉Java语言

[外链图片转存中…(img-6Ub2kcBJ-1711911131572)]

高级UI与自定义view;
自定义view,Android开发的基本功。

[外链图片转存中…(img-SqE0wDGe-1711911131572)]

性能调优;
数据结构算法,设计模式。都是这里面的关键基础和重点需要熟练的。

[外链图片转存中…(img-eiRvl9R9-1711911131572)]

NDK开发;
未来的方向,高薪必会。

[外链图片转存中…(img-hSUDREsK-1711911131573)]

前沿技术;
组件化,热升级,热修复,框架设计

[外链图片转存中…(img-ES5DuNDQ-1711911131573)]

网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。

我在搭建这些技术框架的时候,还整理了系统的高级进阶教程,会比自己碎片化学习效果强太多,CodeChina上可见;

当然,想要深入学习并掌握这些能力,并不简单。关于如何学习,做程序员这一行什么工作强度大家都懂,但是不管工作多忙,每周也要雷打不动的抽出 2 小时用来学习。

不出半年,你就能看出变化!

本文已被CODING开源项目:《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》收录

  • 17
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
常用的Java工具类有很多,以下是一些常见的工具类: 1. org.apache.commons.io.IOUtils:提供了一组用于处理输入输出流的实用方法,如复制流、关闭流等。\[1\] 2. org.apache.commons.io.FileUtils:提供了一组用于操作文件和目录的实用方法,如复制文件、删除文件等。\[2\] 3. org.apache.commons.lang.StringUtils:提供了一组用于处理字符串的实用方法,如判断字符串是否为空、去除字符串的空格等。\[3\] 4. org.apache.http.util.EntityUtils:提供了一组用于处理HTTP实体的实用方法,如获取实体内容、解析实体等。 5. org.apache.commons.lang3.StringUtils:是Apache Commons Lang库的一部分,提供了更多字符串处理的实用方法,如判断字符串是否为数字、反转字符串等。 6. org.apache.commons.io.FilenameUtils:提供了一组用于处理文件名的实用方法,如获取文件名的扩展名、合并路径等。 7. org.springframework.util.StringUtils:是Spring框架的一个工具类,提供了一组用于处理字符串的实用方法,如判断字符串是否为空、去除字符串的空格等。 8. org.apache.commons.lang.ArrayUtils:提供了一组用于处理数组的实用方法,如判断数组是否为空、合并数组等。 这些工具类可以帮助开发人员简化代码,提高开发效率。具体使用哪些工具类取决于项目需求和个人偏好。 #### 引用[.reference_title] - *1* *3* [【Java】Java常用工具类(排名前 16)](https://blog.csdn.net/u011397981/article/details/129688782)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [「Java工具类」验证码工具类java生成验证码工具类](https://blog.csdn.net/lxn39830435731415926/article/details/121259382)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值