Java和Android中一些常用的公共方法
/**
* 通过findStr在getStr的位置,查找相应位置上setStr的值
*
* @param getStr
* 所在位置
* @param setStr
* 查找位置
* @param findStr
* 查找条件
* @return 查找相应的值
*/
public static String findStr(CharSequence[] getStr, CharSequence[] setStr, String findStr) {
int len = getStr.length;
String str = null;
for (int i = 0; i < len; i++) {
if (getStr[i].equals(findStr)) {
str = setStr[i].toString();
}
}
return str;
}
/**
* 获取指定字符串在数组位置
*
* @param charSeq
* @param str
* @return
*/
public static int getIndex(CharSequence[] charSeq, String str) {
int index = 0;
for (int i = 0; i < charSeq.length; i++) {
if (charSeq[i].toString().equals(str)) {
index = i;
break;
}
}
return index;
}
/**
* 时间格式化
*
* @param time
* 秒数
* @return
*/
public static String timeFormat(int time) {
String retString = "";
int hour = (time / 3600);
int minute = ((time - hour * 3600) / 60);
int second = (time - hour * 3600 - minute * 60);
if (hour != 0) {
retString += String.valueOf(hour) + "小时";
}
if (minute != 0) {
retString += String.valueOf(minute) + "分钟";
}
if (second != 0) {
retString += String.valueOf(second) + "秒";
}
return retString;
}
/**
* 改变图片尺寸
*
* @param makeWidth
* @param makeHeight
* @param makeBit
* @return
*/
public static Bitmap makeImg(int makeWidth, int makeHeight, Bitmap makeBit) {
if (makeBit != null) {
float scaleWidth = ((float) makeWidth) / makeBit.getWidth();
float scaleHeight = ((float) makeHeight) / makeBit.getHeight();
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(makeBit, 0, 0, makeBit.getWidth(), makeBit.getHeight(), matrix, true);
return resizedBitmap;
} else {
return null;
}
}
/**
* 改变图片尺寸
*/
public static String createMacStr(String mac) {
return mac.replaceAll(":", "_");
}
/**
* 图片阴影渐变效果
*
* @param originalImage
* @return
*/
public static Bitmap createReflectedImage(Bitmap originalImage) {
final int reflectionGap = 0;
int width = originalImage.getWidth();
int height = originalImage.getHeight();
/** 倒影旋转的角度 **/
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
/** 创建倒影图片 **/
Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height / 2, width, height / 2, matrix, false);
/** 设置新建的画布样式 **/
Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 6), Config.ARGB_8888);
/** 创建画布 **/
Canvas canvas = new Canvas(bitmapWithReflection);
canvas.drawBitmap(originalImage, 0, 0, null);
Paint defaultPaint = new Paint();
canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint);
canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
Paint paint = new Paint();
/** 画出倒影 **/
LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.MIRROR);
paint.setShader(shader);
/** 设置渐变 **/
paint.setXfermode(new PorterDuffXfermode(Mode.DST_ATOP));
canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint);
/** 将画在画布上的图返回 **/
return bitmapWithReflection;
}
/**
* 获取时间戳(字数串格式化yyyyMMddHHmmsssss)
*/
public static String getTimestampStr() {
SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyyMMddHHmmsssss");
Date date = new Date();
return bartDateFormat.format(date);
}
/**
* 获取当前日期(字数串格式化yyyy-MM-dd)
*/
public static String getNowDateStr() {
SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
return bartDateFormat.format(date);
}
/**
* 获取本地Jar包图片
*
* @return Bitmap类型
*/
public static Bitmap getLocalBitmap(URL localPath) {
Bitmap bitmap = null;
try {
URLConnection uConnection = localPath.openConnection();
uConnection.setDoInput(true);
uConnection.connect();
InputStream inStream = uConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(inStream);
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
/**
* 获取文本内容
*
* @param filePath
* @return
*/
public static String getTextFile(String filePath) {
String result = null;
try {
File file = new File(filePath);
BufferedReader bufRead = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while ((result = bufRead.readLine()) != null) {
return result;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 获得文件扩展名
*
* @param fileName
* @return
*/
public static String getFileExtention(String fileName) {
int length = fileName.length();
for (int i = length - 1; i >= 0; i--) {
if (fileName.charAt(i) == '.') {
return fileName.substring(i);
}
}
return fileName;
}
/**
* 截取","字符
*
* @param str
* @return
*/
public static List<String> getName(String str) {
List<String> list = new ArrayList<String>();
String[] cutArray = str.split(",");
int length = cutArray.length;
for (int i = 0; i < length; i++) {
list.add(cutArray[i]);
}
return list;
}
/**
* 读取本地内存图片
*
* @param getFileBitmap 本地图片路径
* @param fileName 本地图片名称
* @return
*/
public static Bitmap getFileBitmap(String filePath, String fileName) {
Bitmap bmp = BitmapFactory.decodeFile(filePath + fileName);
return bmp;
}
/**
* 删除文件夹
*
* @param folder
* @return
*/
public static boolean deleteFolder(File folder) {
boolean result = false;
try {
String childs[] = folder.list();
if (childs == null || childs.length <= 0) {
if (folder.delete()) {
result = true;
}
} else {
for (int i = 0; i < childs.length; i++) {
String childName = childs[i];
String childPath = folder.getPath() + File.separator + childName;
File filePath = new File(childPath);
if (filePath.exists() && filePath.isFile()) {
if (filePath.delete()) {
result = true;
} else {
result = false;
break;
}
} else if (filePath.exists() && filePath.isDirectory()) {
if (deleteFolder(filePath)) {
result = true;
} else {
result = false;
break;
}
}
}
folder.delete();
}
} catch (Exception e) {
result = false;
}
return result;
}
/**
* 复制文件
*
* @param sourceFile 源文件
* @param targetFile 目标文件
* @throws IOException
*/
public static void copyFile(File sourceFile, File targetFile) throws IOException {
/** 新建文件输入流并对它进行缓冲 **/
FileInputStream input = new FileInputStream(sourceFile);
BufferedInputStream inBuff = new BufferedInputStream(input);
/** 新建文件输出流并对它进行缓冲 **/
FileOutputStream output = new FileOutputStream(targetFile);
BufferedOutputStream outBuff = new BufferedOutputStream(output);
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
/** 刷新此缓冲的输出流 **/
outBuff.flush();
inBuff.close();
outBuff.close();
output.close();
input.close();
}
/**
* 复制文件夹
*
* @param sourceDir 源文件夹
* @param targetDir 目标文件夹
* @throws IOException
*/
public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {
(new File(targetDir)).mkdirs();
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
/** 源文件 **/
File sourceFile = file[i];
/** 目标文件 **/
File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
copyFile(sourceFile, targetFile);
}
if (file[i].isDirectory()) {
/** 源文件夹 **/
String dir1 = sourceDir + "/" + file[i].getName();
/** 源文件夹 **/
String dir2 = targetDir + "/" + file[i].getName();
copyDirectiory(dir1, dir2);
}
}
}
/**
* 删除文件夹下的指定文件
*
* @param folder 所在文件夹
* @param str 指定模糊的字符串
* @return
*/
public static boolean deleteAssignFolder(File folder, String str) {
boolean result = false;
try {
String childs[] = folder.list();
if (childs == null || childs.length <= 0) {
result = false;
} else {
for (int i = 0; i < childs.length; i++) {
String childName = childs[i];
String subStr = childName.substring(0, childName.indexOf("_"));
if (str.equals(subStr)) {
String childPath = folder.getPath() + File.separator + childName;
File filePath = new File(childPath);
if (filePath.exists() && filePath.isFile()) {
if (filePath.delete()) {
result = true;
} else {
result = false;
break;
}
} else if (filePath.exists() && filePath.isDirectory()) {
if (deleteAssignFolder(filePath, str)) {
result = true;
} else {
result = false;
break;
}
}
}
}
}
} catch (Exception e) {
result = false;
}
return result;
}
/**
* 创建文件同时初始化文件内容
*
* @param filename
* @param filecontent
* @return
*/
public static boolean createFileContent(String filename, String filecontent) {
try {
File f = new File(filename);
if (f.exists() && f.isFile())
f.delete();
FileOutputStream fos = new FileOutputStream(f, true);
fos.write(filecontent.getBytes());
fos.close();
return true;
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
/**
* 创建文件同时初始化文件内容
*/
public static String createDirectory(String filepath) {
File f = new File(filepath);
if (!f.exists())
f.mkdirs();
return filepath;
}
/**
* 截取扩展名'.'之前的文件名
*
* @param fileName
* @return
*/
public static String getFileName(String fileName) {
if ((fileName != null) && (fileName.length() > 0)) {
int i = fileName.lastIndexOf('.');
if ((i > -1) && (i < (fileName.length()))) {
return fileName.substring(0, i);
}
}
return fileName;
}
对MD5加密的操作:
//十六进制下数字到字符的映射数组
private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
/** 把inputString加密 */
public static String createPassword(String inputString) {
return encodeByMD5(inputString);
}
/**
*
* Creation Date:2008-3-14
* 验证输入的密码是否正确
* @param password 加密后的源密码
* @param inputString 输入字符串
* @return boolean true为真,false为假
* @Author tianw
*/
public static boolean authenticatePassword(String password,
String inputString) {
if (password.equals(encodeByMD5(inputString))) {
return true;
} else {
return false;
}
}
/** 对字符串进行MD5加密 */
private static String encodeByMD5(String originString) {
if (originString != null) {
try {
// 创建具有指定算法名称的信息摘要
MessageDigest md = MessageDigest.getInstance("MD5");
// 使用指定的字节数组对摘要进行最后更新,然后完成摘要计算
byte[] results = md.digest(originString.getBytes());
// 将得到的字节数组变成字符串返回
String resultString = byteArrayToHexString(results);
return resultString.toUpperCase();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
/**
*
* Creation Date:2008-3-14
* 转换字节数组为十六进制字符串
* @param b 字节数组
* @return String 十六进制字符串
* @Author tianw
*/
private static String byteArrayToHexString(byte[] b) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String ss = byteToHexString(b[i]);
resultSb.append(ss);
}
return resultSb.toString();
}
/** 将一个字节转化成十六进制形式的字符串 */
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n = 256 + n;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
/**
* Post提交
*
* @param linkAddress 请求地址
* @param map Key:参数,Value:内容
* @param timeOut 超时时间
* @return
*/
public static String requestPost(String linkAddress, Map<String, String> map, int timeOut) {
String result = null;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, timeOut * 1000);
HttpConnectionParams.setSoTimeout(httpParams, 60 * 1000);
HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
HttpClient httpClient = new DefaultHttpClient(httpParams);
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
try {
HttpPost httpost = new HttpPost(linkAddress);
if (map != null) {
List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
for (Map.Entry<String, String> entry : map.entrySet()) {
postData.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpost.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8));
}
HttpResponse response = httpClient.execute(httpost); // 执行
String httpStatus = response.getStatusLine().toString();
if (httpStatus.indexOf("4") > 0 || httpStatus.indexOf("5") > 0) {
result = "error"; // 如果响应码为4开头,则代表访问不成功
}
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
String backStream = EntityUtils.toString(httpEntity); // 回写内容
result = backStream.toString();
httpEntity.consumeContent();
}
} catch (SocketTimeoutException e) {
result = "SoError";
} catch (IOException e) {
result = "IOError";
} catch (Exception e) {
result = "error";
} finally {
httpClient.getConnectionManager().shutdown();
}
return result;
}
/**
* 生成JSONArray
*
* @param map Key:参数,Value:内容
* @return
*/
public static String createJSONArray(Map<String, String> map) {
String result = null;
try {
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
for (Map.Entry<String, String> entry : map.entrySet()) {
jsonObject.put(entry.getKey(), entry.getValue());
}
jsonArray.put(jsonObject);
result = jsonArray.toString();
} catch (Exception e) {
}
return result;
}
/**
* 下载文件并保存
*
* @param fileUrl 下载文件地址
* @param filePath 保存文件位置
* @param fileName 保存文件名称
* @return
*/
public static boolean saveDownFile(String fileUrl, String filePath, String fileName) {
try {
URL url = new URL(fileUrl);
File dirFile = new File(filePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
FileOutputStream fos = new FileOutputStream(new File(filePath + fileName));
byte[] buffer = new byte[256];
int current = 0;
while ((current = is.read(buffer, 0, 256)) != -1) {
fos.write(buffer, 0, current);
}
fos.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
注明:QQ技术交流群:108614806 感兴趣的加一下。