StringUtils.java
12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
package com.cnlive.goldenline.util;
import android.annotation.TargetApi;
import android.nfc.NdefRecord;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import com.orhanobut.logger.Logger;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 字符串工具类
*
* @author zuoxian
*/
public class StringUtils {
public static final String EMPTY = "";
private static final String TAG = "StringUtils";
private static final double KB = 1024.0;
private static final double MB = 1048576.0;
private static final double GB = 1073741824.0;
/**
* 将流转成字符串
*
* @param is 输入流
* @return
* @throws Exception
*/
public static String convertStreamToString(@NonNull InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
}
/**
* 将文件转成字符串
*
* @param file 文件
* @return
* @throws Exception
*/
@NonNull
public static String getStringFromFile(@NonNull File file) throws Exception {
FileInputStream fin = new FileInputStream(file);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
public static char chatAt(@Nullable String pinyin, int index) {
if (pinyin != null && pinyin.length() > 0)
return pinyin.charAt(index);
return ' ';
}
/**
* 获取字符串宽度
*/
public static float GetTextWidth(@NonNull String Sentence, float Size) {
if (isEmpty(Sentence))
return 0;
TextPaint FontPaint = new TextPaint();
FontPaint.setTextSize(Size);
return FontPaint.measureText(Sentence.trim()) + (int) (Size * 0.1); // 留点余地
}
/**********************************************
* 检测手机号码是否符合格式
*
* @param number 手机号码
* @return true 手机号码符合规范 flase 手机号不符合规范
*/
public static boolean checkPhoneNumber(String number) {
if (TextUtils.isEmpty(number)) {
return false;
}
if (number.length() != 11) {
return false;
}
try {
Pattern p = Pattern.compile("(13[0-9]|14[57]|15[012356789]|18[0-9]|17[0-9])\\d{8}");
Matcher m = p.matcher(number);
return m.matches();
} catch (Exception e) {
return false;
}
}
/**
* 拼接数组
*
* @param array
* @param separator
* @return
*/
public static String join(@Nullable final ArrayList<String> array,
final String separator) {
StringBuffer result = new StringBuffer();
if (array != null && array.size() > 0) {
for (String str : array) {
result.append(str);
result.append(separator);
}
result.delete(result.length() - 1, result.length());
}
return result.toString();
}
public static String join(@Nullable final Iterator<String> iter,
final String separator) {
StringBuffer result = new StringBuffer();
if (iter != null) {
while (iter.hasNext()) {
String key = iter.next();
result.append(key);
result.append(separator);
}
if (result.length() > 0)
result.delete(result.length() - 1, result.length());
}
return result.toString();
}
/**
* 检验是否数字与小数点
*
* @param source
* @return
*/
public static boolean pureNum(@NonNull String source) {
if (isEmpty(source)) {
return false;
}
if ("null".equalsIgnoreCase(source)) {
return false;
}
Pattern pattern = Pattern.compile("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
Matcher match = pattern.matcher(source);
return match.matches();
}
/**
* 调整EditText hint字体大小
*
* @param hint 显示的提示字符串
* @param hintTextSize 提示字体大小
* @return
*/
@NonNull
public static SpannableString fromatETHint(String hint, int hintTextSize) {
SpannableString ss = new SpannableString(hint);
// 新建一个属性对象,设置文字的大小
AbsoluteSizeSpan ass = new AbsoluteSizeSpan(hintTextSize, true);
// 附加属性到文本
ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return new SpannableString(ss);
}
/**
* 按指定格式 格式化 数字
*
* @param num
* @param pattern
* @return
*/
public static String formatnum(double num, String pattern) {
DecimalFormat df = new DecimalFormat(pattern);
return df.format(num);
}
/**
* 判断字符串是否为空
*
* @param str
* @return
*/
public static boolean isEmpty(@Nullable String str) {
return str == null || str.length() == 0 || str == "null" || "null".equalsIgnoreCase(str);
}
/**
* @param str
* @return
*/
@NonNull
public static String trim(@Nullable String str) {
return str == null ? EMPTY : str.trim();
}
/**
* 转换时间显示
*
* @param time 毫秒
* @return
*/
public static String generateTime(long time) {
int totalSeconds = (int) (time / 1000);
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
return hours > 0 ? String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes,
seconds) : String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
}
/**
* 根据秒速获取时间格式
*/
public static String gennerTime(int totalSeconds) {
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
return String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
}
/**
* 转换文件大小
*
* @param size
* @return
*/
public static String generateFileSize(long size) {
String fileSize;
if (size < KB)
fileSize = size + "B";
else if (size < MB)
fileSize = String.format("%.1f", size / KB) + "KB";
else if (size < GB)
fileSize = String.format("%.1f", size / MB) + "MB";
else
fileSize = String.format("%.1f", size / GB) + "GB";
return fileSize;
}
@NonNull
public static String getTimeDiff(long time) {
// Calendar cal = Calendar.getInstance();
long diff = 0;
// Date dnow = cal.getTime();
String str = "";
diff = System.currentTimeMillis() - time;
if (diff > 2592000000L) {// 30 * 24 * 60 * 60 * 1000=2592000000 毫秒
str = "1个月前";
} else if (diff > 1814400000) {// 21 * 24 * 60 * 60 * 1000=1814400000 毫秒
str = "3周前";
} else if (diff > 1209600000) {// 14 * 24 * 60 * 60 * 1000=1209600000 毫秒
str = "2周前";
} else if (diff > 604800000) {// 7 * 24 * 60 * 60 * 1000=604800000 毫秒
str = "1周前";
} else if (diff > 86400000) { // 24 * 60 * 60 * 1000=86400000 毫秒
// System.out.println("X天前");
str = (int) Math.floor(diff / 86400000f) + "天前";
} else if (diff > 18000000) {// 5 * 60 * 60 * 1000=18000000 毫秒
// System.out.println("X小时前");
str = (int) Math.floor(diff / 18000000f) + "小时前";
} else if (diff > 60000) {// 1 * 60 * 1000=60000 毫秒
// System.out.println("X分钟前");
str = (int) Math.floor(diff / 60000) + "分钟前";
} else {
str = (int) Math.floor(diff / 1000) + "秒前";
}
return str;
}
/**
* 截取字符串
*
* @param search 待搜索的字符串
* @param start 起始字符串 例如:<title>
* @param end 结束字符串 例如:</title>
* @param defaultValue
* @return
*/
public static String substring(@NonNull String search, @NonNull String start, @NonNull String end,
String defaultValue) {
int start_len = start.length();
int start_pos = StringUtils.isEmpty(start) ? 0 : search.indexOf(start);
if (start_pos > -1) {
int end_pos = StringUtils.isEmpty(end) ? -1 : search.indexOf(end,
start_pos + start_len);
if (end_pos > -1)
return search.substring(start_pos + start.length(), end_pos);
else
return search.substring(start_pos + start.length());
}
return defaultValue;
}
/**
* 截取字符串
*
* @param search 待搜索的字符串
* @param start 起始字符串 例如:<title>
* @param end 结束字符串 例如:</title>
* @return
*/
public static String substring(@NonNull String search, @NonNull String start, @NonNull String end) {
return substring(search, start, end, "");
}
/**
* 拼接字符串
*
* @param strs
* @return
*/
public static String concat(@Nullable String... strs) {
StringBuffer result = new StringBuffer();
if (strs != null) {
for (String str : strs) {
if (str != null)
result.append(str);
}
}
return result.toString();
}
/**
* 获取中文字符个数
*/
public static int getChineseCharCount(@NonNull String str) {
String tempStr;
int count = 0;
for (int i = 0; i < str.length(); i++) {
tempStr = String.valueOf(str.charAt(i));
if (tempStr.getBytes().length == 3) {
count++;
}
}
return count;
}
/**
* 获取英文字符个数
*/
public static int getEnglishCount(@NonNull String str) {
String tempStr;
int count = 0;
for (int i = 0; i < str.length(); i++) {
tempStr = String.valueOf(str.charAt(i));
if (!(tempStr.getBytes().length == 3)) {
count++;
}
}
return count;
}
public static String encode(String url) {
try {
return URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
Logger.e(TAG, e.getMessage(), e);
}
return url;
}
@NonNull
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static NdefRecord createTextRecord(@NonNull String payload, @NonNull Locale locale, boolean encodeInUtf8) {
byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII"));
Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16");
byte[] textBytes = payload.getBytes(utfEncoding);
int utfBit = encodeInUtf8 ? 0 : (1 << 7);
char status = (char) (utfBit + langBytes.length);
byte[] data = new byte[1 + langBytes.length + textBytes.length];
data[0] = (byte) status;
System.arraycopy(langBytes, 0, data, 1, langBytes.length);
System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
NdefRecord.RTD_TEXT, new byte[0], data);
return record;
}
@Nullable
public static String yMDtoMD(@Nullable String str) {
if (str == null) return "";
if (str.length() == 8) {
String month = str.substring(4, 6);
String day = str.substring(6, 8);
return month + "-" + day;
} else {
return str;
}
}
public static String strToDateLong() {
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("MM-dd HH:mm");
String strtodate = formatter.format(date);
return strtodate;
}
}