}
63 | * @return if file not exist, return null, else return content of file
64 | * @throws RuntimeException if an error occurs while operator BufferedReader
65 | */
66 | public static StringBuilder readFile(String filePath, String charsetName) {
67 | File file = new File(filePath);
68 | StringBuilder fileContent = new StringBuilder("");
69 | if (file == null || !file.isFile()) {
70 | return null;
71 | }
72 |
73 | BufferedReader reader = null;
74 | try {
75 | InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
76 | reader = new BufferedReader(is);
77 | String line = null;
78 | while ((line = reader.readLine()) != null) {
79 | if (!fileContent.toString().equals("")) {
80 | fileContent.append("\r\n");
81 | }
82 | fileContent.append(line);
83 | }
84 | reader.close();
85 | return fileContent;
86 | } catch (IOException e) {
87 | throw new RuntimeException("IOException occurred. ", e);
88 | } finally {
89 | if (reader != null) {
90 | try {
91 | reader.close();
92 | } catch (IOException e) {
93 | throw new RuntimeException("IOException occurred. ", e);
94 | }
95 | }
96 | }
97 | }
98 |
99 | /**
100 | * write file
101 | *
102 | * @param filePath
103 | * @param content
104 | * @param append is append, if true, write to the end of file, else clear content of file and write into it
105 | * @return return false if content is empty, true otherwise
106 | * @throws RuntimeException if an error occurs while operator FileWriter
107 | */
108 | public static boolean writeFile(String filePath, String content, boolean append) {
109 | if (StringUtils.isEmpty(content)) {
110 | return false;
111 | }
112 |
113 | FileWriter fileWriter = null;
114 | try {
115 | makeDirs(filePath);
116 | fileWriter = new FileWriter(filePath, append);
117 | fileWriter.write(content);
118 | fileWriter.close();
119 | return true;
120 | } catch (IOException e) {
121 | throw new RuntimeException("IOException occurred. ", e);
122 | } finally {
123 | if (fileWriter != null) {
124 | try {
125 | fileWriter.close();
126 | } catch (IOException e) {
127 | throw new RuntimeException("IOException occurred. ", e);
128 | }
129 | }
130 | }
131 | }
132 |
133 | /**
134 | * write file
135 | *
136 | * @param filePath
137 | * @param contentList
138 | * @param append is append, if true, write to the end of file, else clear content of file and write into it
139 | * @return return false if contentList is empty, true otherwise
140 | * @throws RuntimeException if an error occurs while operator FileWriter
141 | */
142 | public static boolean writeFile(String filePath, List contentList, boolean append) {
143 | if (ListUtils.isEmpty(contentList)) {
144 | return false;
145 | }
146 |
147 | FileWriter fileWriter = null;
148 | try {
149 | makeDirs(filePath);
150 | fileWriter = new FileWriter(filePath, append);
151 | int i = 0;
152 | for (String line : contentList) {
153 | if (i++ > 0) {
154 | fileWriter.write("\r\n");
155 | }
156 | fileWriter.write(line);
157 | }
158 | fileWriter.close();
159 | return true;
160 | } catch (IOException e) {
161 | throw new RuntimeException("IOException occurred. ", e);
162 | } finally {
163 | if (fileWriter != null) {
164 | try {
165 | fileWriter.close();
166 | } catch (IOException e) {
167 | throw new RuntimeException("IOException occurred. ", e);
168 | }
169 | }
170 | }
171 | }
172 |
173 | /**
174 | * write file, the string will be written to the begin of the file
175 | *
176 | * @param filePath
177 | * @param content
178 | * @return
179 | */
180 | public static boolean writeFile(String filePath, String content) {
181 | return writeFile(filePath, content, false);
182 | }
183 |
184 | /**
185 | * write file, the string list will be written to the begin of the file
186 | *
187 | * @param filePath
188 | * @param contentList
189 | * @return
190 | */
191 | public static boolean writeFile(String filePath, List contentList) {
192 | return writeFile(filePath, contentList, false);
193 | }
194 |
195 | /**
196 | * write file, the bytes will be written to the begin of the file
197 | *
198 | * @param filePath
199 | * @param stream
200 | * @return
201 | * @see {@link #writeFile(String, InputStream, boolean)}
202 | */
203 | public static boolean writeFile(String filePath, InputStream stream) {
204 | return writeFile(filePath, stream, false);
205 | }
206 |
207 | /**
208 | * write file
209 | *
210 | * @param file the file to be opened for writing.
211 | * @param stream the input stream
212 | * @param append if true
, then bytes will be written to the end of the file rather than the beginning
213 | * @return return true
214 | * @throws RuntimeException if an error occurs while operator FileOutputStream
215 | */
216 | public static boolean writeFile(String filePath, InputStream stream, boolean append) {
217 | return writeFile(filePath != null ? new File(filePath) : null, stream, append);
218 | }
219 |
220 | /**
221 | * write file, the bytes will be written to the begin of the file
222 | *
223 | * @param file
224 | * @param stream
225 | * @return
226 | * @see {@link #writeFile(File, InputStream, boolean)}
227 | */
228 | public static boolean writeFile(File file, InputStream stream) {
229 | return writeFile(file, stream, false);
230 | }
231 |
232 | /**
233 | * write file
234 | *
235 | * @param file the file to be opened for writing.
236 | * @param stream the input stream
237 | * @param append if true
, then bytes will be written to the end of the file rather than the beginning
238 | * @return return true
239 | * @throws RuntimeException if an error occurs while operator FileOutputStream
240 | */
241 | public static boolean writeFile(File file, InputStream stream, boolean append) {
242 | OutputStream o = null;
243 | try {
244 | makeDirs(file.getAbsolutePath());
245 | o = new FileOutputStream(file, append);
246 | byte data[] = new byte[1024];
247 | int length = -1;
248 | while ((length = stream.read(data)) != -1) {
249 | o.write(data, 0, length);
250 | }
251 | o.flush();
252 | return true;
253 | } catch (FileNotFoundException e) {
254 | throw new RuntimeException("FileNotFoundException occurred. ", e);
255 | } catch (IOException e) {
256 | throw new RuntimeException("IOException occurred. ", e);
257 | } finally {
258 | if (o != null) {
259 | try {
260 | o.close();
261 | stream.close();
262 | } catch (IOException e) {
263 | throw new RuntimeException("IOException occurred. ", e);
264 | }
265 | }
266 | }
267 | }
268 |
269 | /**
270 | * move file
271 | *
272 | * @param sourceFilePath
273 | * @param destFilePath
274 | */
275 | public static void moveFile(String sourceFilePath, String destFilePath) {
276 | if (TextUtils.isEmpty(sourceFilePath) || TextUtils.isEmpty(destFilePath)) {
277 | throw new RuntimeException("Both sourceFilePath and destFilePath cannot be null.");
278 | }
279 | moveFile(new File(sourceFilePath), new File(destFilePath));
280 | }
281 |
282 | /**
283 | * move file
284 | *
285 | * @param srcFile
286 | * @param destFile
287 | */
288 | public static void moveFile(File srcFile, File destFile) {
289 | boolean rename = srcFile.renameTo(destFile);
290 | if (!rename) {
291 | copyFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath());
292 | deleteFile(srcFile.getAbsolutePath());
293 | }
294 | }
295 |
296 | /**
297 | * copy file
298 | *
299 | * @param sourceFilePath
300 | * @param destFilePath
301 | * @return
302 | * @throws RuntimeException if an error occurs while operator FileOutputStream
303 | */
304 | public static boolean copyFile(String sourceFilePath, String destFilePath) {
305 | InputStream inputStream = null;
306 | try {
307 | inputStream = new FileInputStream(sourceFilePath);
308 | } catch (FileNotFoundException e) {
309 | throw new RuntimeException("FileNotFoundException occurred. ", e);
310 | }
311 | return writeFile(destFilePath, inputStream);
312 | }
313 |
314 | /**
315 | * read file to string list, a element of list is a line
316 | *
317 | * @param filePath
318 | * @param charsetName The name of a supported {@link java.nio.charset.Charset
charset}
319 | * @return if file not exist, return null, else return content of file
320 | * @throws RuntimeException if an error occurs while operator BufferedReader
321 | */
322 | public static List readFileToList(String filePath, String charsetName) {
323 | File file = new File(filePath);
324 | List fileContent = new ArrayList();
325 | if (file == null || !file.isFile()) {
326 | return null;
327 | }
328 |
329 | BufferedReader reader = null;
330 | try {
331 | InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
332 | reader = new BufferedReader(is);
333 | String line = null;
334 | while ((line = reader.readLine()) != null) {
335 | fileContent.add(line);
336 | }
337 | reader.close();
338 | return fileContent;
339 | } catch (IOException e) {
340 | throw new RuntimeException("IOException occurred. ", e);
341 | } finally {
342 | if (reader != null) {
343 | try {
344 | reader.close();
345 | } catch (IOException e) {
346 | throw new RuntimeException("IOException occurred. ", e);
347 | }
348 | }
349 | }
350 | }
351 |
352 | /**
353 | * get file name from path, not include suffix
354 | *
355 | *
356 | * getFileNameWithoutExtension(null) = null
357 | * getFileNameWithoutExtension("") = ""
358 | * getFileNameWithoutExtension(" ") = " "
359 | * getFileNameWithoutExtension("abc") = "abc"
360 | * getFileNameWithoutExtension("a.mp3") = "a"
361 | * getFileNameWithoutExtension("a.b.rmvb") = "a.b"
362 | * getFileNameWithoutExtension("c:\\") = ""
363 | * getFileNameWithoutExtension("c:\\a") = "a"
364 | * getFileNameWithoutExtension("c:\\a.b") = "a"
365 | * getFileNameWithoutExtension("c:a.txt\\a") = "a"
366 | * getFileNameWithoutExtension("/home/admin") = "admin"
367 | * getFileNameWithoutExtension("/home/admin/a.txt/b.mp3") = "b"
368 | *
369 | *
370 | * @param filePath
371 | * @return file name from path, not include suffix
372 | * @see
373 | */
374 | public static String getFileNameWithoutExtension(String filePath) {
375 | if (StringUtils.isEmpty(filePath)) {
376 | return filePath;
377 | }
378 |
379 | int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
380 | int filePosi = filePath.lastIndexOf(File.separator);
381 | if (filePosi == -1) {
382 | return (extenPosi == -1 ? filePath : filePath.substring(0, extenPosi));
383 | }
384 | if (extenPosi == -1) {
385 | return filePath.substring(filePosi + 1);
386 | }
387 | return (filePosi < extenPosi ? filePath.substring(filePosi + 1, extenPosi) : filePath.substring(filePosi + 1));
388 | }
389 |
390 | /**
391 | * get file name from path, include suffix
392 | *
393 | *
394 | * getFileName(null) = null
395 | * getFileName("") = ""
396 | * getFileName(" ") = " "
397 | * getFileName("a.mp3") = "a.mp3"
398 | * getFileName("a.b.rmvb") = "a.b.rmvb"
399 | * getFileName("abc") = "abc"
400 | * getFileName("c:\\") = ""
401 | * getFileName("c:\\a") = "a"
402 | * getFileName("c:\\a.b") = "a.b"
403 | * getFileName("c:a.txt\\a") = "a"
404 | * getFileName("/home/admin") = "admin"
405 | * getFileName("/home/admin/a.txt/b.mp3") = "b.mp3"
406 | *
407 | *
408 | * @param filePath
409 | * @return file name from path, include suffix
410 | */
411 | public static String getFileName(String filePath) {
412 | if (StringUtils.isEmpty(filePath)) {
413 | return filePath;
414 | }
415 |
416 | int filePosi = filePath.lastIndexOf(File.separator);
417 | return (filePosi == -1) ? filePath : filePath.substring(filePosi + 1);
418 | }
419 |
420 | /**
421 | * get folder name from path
422 | *
423 | *
424 | * getFolderName(null) = null
425 | * getFolderName("") = ""
426 | * getFolderName(" ") = ""
427 | * getFolderName("a.mp3") = ""
428 | * getFolderName("a.b.rmvb") = ""
429 | * getFolderName("abc") = ""
430 | * getFolderName("c:\\") = "c:"
431 | * getFolderName("c:\\a") = "c:"
432 | * getFolderName("c:\\a.b") = "c:"
433 | * getFolderName("c:a.txt\\a") = "c:a.txt"
434 | * getFolderName("c:a\\b\\c\\d.txt") = "c:a\\b\\c"
435 | * getFolderName("/home/admin") = "/home"
436 | * getFolderName("/home/admin/a.txt/b.mp3") = "/home/admin/a.txt"
437 | *
438 | *
439 | * @param filePath
440 | * @return
441 | */
442 | public static String getFolderName(String filePath) {
443 |
444 | if (StringUtils.isEmpty(filePath)) {
445 | return filePath;
446 | }
447 |
448 | int filePosi = filePath.lastIndexOf(File.separator);
449 | return (filePosi == -1) ? "" : filePath.substring(0, filePosi);
450 | }
451 |
452 | /**
453 | * get suffix of file from path
454 | *
455 | *
456 | * getFileExtension(null) = ""
457 | * getFileExtension("") = ""
458 | * getFileExtension(" ") = " "
459 | * getFileExtension("a.mp3") = "mp3"
460 | * getFileExtension("a.b.rmvb") = "rmvb"
461 | * getFileExtension("abc") = ""
462 | * getFileExtension("c:\\") = ""
463 | * getFileExtension("c:\\a") = ""
464 | * getFileExtension("c:\\a.b") = "b"
465 | * getFileExtension("c:a.txt\\a") = ""
466 | * getFileExtension("/home/admin") = ""
467 | * getFileExtension("/home/admin/a.txt/b") = ""
468 | * getFileExtension("/home/admin/a.txt/b.mp3") = "mp3"
469 | *
470 | *
471 | * @param filePath
472 | * @return
473 | */
474 | public static String getFileExtension(String filePath) {
475 | if (StringUtils.isBlank(filePath)) {
476 | return filePath;
477 | }
478 |
479 | int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
480 | int filePosi = filePath.lastIndexOf(File.separator);
481 | if (extenPosi == -1) {
482 | return "";
483 | }
484 | return (filePosi >= extenPosi) ? "" : filePath.substring(extenPosi + 1);
485 | }
486 |
487 | /**
488 | * Creates the directory named by the trailing filename of this file, including the complete directory path required
489 | * to create this directory.
490 | *
491 | *
492 | * Attentions:
493 | * - makeDirs("C:\\Users\\Trinea") can only create users folder
494 | * - makeFolder("C:\\Users\\Trinea\\") can create Trinea folder
495 | *
496 | *
497 | * @param filePath
498 | * @return true if the necessary directories have been created or the target directory already exists, false one of
499 | * the directories can not be created.
500 | *
501 | * - if {@link FileUtils#getFolderName(String)} return null, return false
502 | * - if target directory already exists, return true
503 | * - return {@link File#makeFolder}
504 | *
505 | */
506 | public static boolean makeDirs(String filePath) {
507 | String folderName = getFolderName(filePath);
508 | if (StringUtils.isEmpty(folderName)) {
509 | return false;
510 | }
511 |
512 | File folder = new File(folderName);
513 | return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
514 | }
515 |
516 | /**
517 | * @param filePath
518 | * @return
519 | * @see #makeDirs(String)
520 | */
521 | public static boolean makeFolders(String filePath) {
522 | return makeDirs(filePath);
523 | }
524 |
525 | /**
526 | * Indicates if this file represents a file on the underlying file system.
527 | *
528 | * @param filePath
529 | * @return
530 | */
531 | public static boolean isFileExist(String filePath) {
532 | if (StringUtils.isBlank(filePath)) {
533 | return false;
534 | }
535 |
536 | File file = new File(filePath);
537 | return (file.exists() && file.isFile());
538 | }
539 |
540 | /**
541 | * Indicates if this file represents a directory on the underlying file system.
542 | *
543 | * @param directoryPath
544 | * @return
545 | */
546 | public static boolean isFolderExist(String directoryPath) {
547 | if (StringUtils.isBlank(directoryPath)) {
548 | return false;
549 | }
550 |
551 | File dire = new File(directoryPath);
552 | return (dire.exists() && dire.isDirectory());
553 | }
554 |
555 | /**
556 | * delete file or directory
557 | *
558 | * - if path is null or empty, return true
559 | * - if path not exist, return true
560 | * - if path exist, delete recursion. return true
561 | *
562 | *
563 | * @param path
564 | * @return
565 | */
566 | public static boolean deleteFile(String path) {
567 | if (StringUtils.isBlank(path)) {
568 | return true;
569 | }
570 |
571 | File file = new File(path);
572 | if (!file.exists()) {
573 | return true;
574 | }
575 | if (file.isFile()) {
576 | return file.delete();
577 | }
578 | if (!file.isDirectory()) {
579 | return false;
580 | }
581 | for (File f : file.listFiles()) {
582 | if (f.isFile()) {
583 | f.delete();
584 | } else if (f.isDirectory()) {
585 | deleteFile(f.getAbsolutePath());
586 | }
587 | }
588 | return file.delete();
589 | }
590 |
591 | /**
592 | * get file size
593 | *
594 | * - if path is null or empty, return -1
595 | * - if path exist and it is a file, return file size, else return -1
596 | *
597 | *
598 | * @param path
599 | * @return returns the length of this file in bytes. returns -1 if the file does not exist.
600 | */
601 | public static long getFileSize(String path) {
602 | if (StringUtils.isBlank(path)) {
603 | return -1;
604 | }
605 |
606 | File file = new File(path);
607 | return (file.exists() && file.isFile() ? file.length() : -1);
608 | }
609 | }
610 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/java/com/test/poiword/utils/ImageUtils.java:
--------------------------------------------------------------------------------
1 | package com.test.poiword.utils;
2 |
3 | import android.graphics.Bitmap;
4 | import android.graphics.Bitmap.Config;
5 | import android.graphics.BitmapFactory;
6 | import android.graphics.Canvas;
7 | import android.graphics.LinearGradient;
8 | import android.graphics.Matrix;
9 | import android.graphics.Paint;
10 | import android.graphics.PixelFormat;
11 | import android.graphics.PorterDuff.Mode;
12 | import android.graphics.PorterDuffXfermode;
13 | import android.graphics.Rect;
14 | import android.graphics.RectF;
15 | import android.graphics.Shader.TileMode;
16 | import android.graphics.drawable.Drawable;
17 | import android.util.Log;
18 | import android.view.View;
19 |
20 | import java.io.ByteArrayInputStream;
21 | import java.io.ByteArrayOutputStream;
22 | import java.io.File;
23 | import java.io.FileInputStream;
24 | import java.io.IOException;
25 | import java.io.InputStream;
26 | import java.net.HttpURLConnection;
27 | import java.net.MalformedURLException;
28 | import java.net.URL;
29 |
30 | /**
31 | * Created by ${dzm} on 2015/9/16 0016.
32 | */
33 | public class ImageUtils {
34 | /**
35 | * @param url
36 | * @return
37 | */
38 | public Bitmap returnBitMapByUrl(String url) {
39 | URL myFileUrl = null;
40 | Bitmap bitmap = null;
41 | try {
42 | myFileUrl = new URL(url);
43 | } catch (MalformedURLException e) {
44 | e.printStackTrace();
45 | }
46 | try {
47 | HttpURLConnection conn = (HttpURLConnection) myFileUrl
48 | .openConnection();
49 | conn.setDoInput(true);
50 | conn.connect();
51 | InputStream is = conn.getInputStream();
52 | bitmap = BitmapFactory.decodeStream(is);
53 | is.close();
54 | } catch (IOException e) {
55 | e.printStackTrace();
56 | }
57 | //Log.v(tag, bitmap.toString());
58 | return bitmap;
59 | }
60 |
61 | /**
62 | * @param path
63 | * @return
64 | */
65 | public Bitmap returnBmpByFilePath(String path) {
66 | Bitmap bitmap = null;
67 | File file = new File(path);
68 | try {
69 | if (file.exists()) {
70 | FileInputStream is = new FileInputStream(file);
71 | BitmapFactory.Options options = new BitmapFactory.Options();
72 | bitmap = BitmapFactory.decodeFile(path, options);//decodeStream(is);
73 | is.close();
74 | }
75 | } catch (Exception e) {
76 | e.printStackTrace();
77 | }
78 | //Log.v(tag, bitmap.toString());
79 | return bitmap;
80 | }
81 |
82 | /**
83 | * @param path
84 | * @param w
85 | * @param h
86 | */
87 | public Bitmap getZoomBmp4Path(String path, int w, int h) {
88 | Bitmap bitmap = BitmapFactory.decodeFile(path);
89 | if (bitmap != null) {
90 | int width = bitmap.getWidth();
91 | int height = bitmap.getHeight();
92 | Matrix matrix = new Matrix();
93 | float scaleWidht = ((float) w / width);
94 | float scaleHeight = ((float) h / height);
95 | matrix.postScale(scaleWidht, scaleHeight);
96 | Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
97 | BitmapFactory.Options options = new BitmapFactory.Options();
98 | return newbmp;
99 | } else {
100 | return null;
101 | }
102 | }
103 |
104 | public Bitmap getZoomBmpByDecodePath(String path, int w, int h) {
105 | BitmapFactory.Options options = new BitmapFactory.Options();
106 | options.inJustDecodeBounds = true;
107 | BitmapFactory.decodeFile(path, options);
108 | options.inSampleSize = calculateInSampleSize(options, w, h);
109 | options.inJustDecodeBounds = false;
110 | return BitmapFactory.decodeFile(path, options);
111 | }
112 |
113 | /**
114 | *
115 | * @param path
116 | * @return
117 | */
118 | public static Bitmap returnBmpByPath(String path) {
119 | Bitmap bitmap = null;
120 | File file = new File(path);
121 | try {
122 | if(file.exists()) {
123 | FileInputStream is = new FileInputStream(file);
124 | bitmap = BitmapFactory.decodeStream(is);
125 | is.close();
126 | }
127 | } catch (IOException e) {
128 | e.printStackTrace();
129 | }
130 | //Log.v(tag, bitmap.toString());
131 |
132 | return bitmap;
133 |
134 | }
135 |
136 | /**
137 | * 质量压缩
138 | * @param image
139 | * @return
140 | */
141 | public static Bitmap compressImage(Bitmap image) {
142 |
143 | ByteArrayOutputStream baos = new ByteArrayOutputStream();
144 | image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
145 | int options = 100;
146 | while ( baos.toByteArray().length / 1024>100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩
147 | baos.reset();//重置baos即清空baos
148 | image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
149 | options -= 10;//每次都减少10
150 | }
151 | ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
152 | Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
153 | return bitmap;
154 | }
155 |
156 | /**
157 | * 图片按比例大小压缩方法(根据路径获取图片并压缩)
158 | * @param srcPath
159 | * @return
160 | */
161 | public static Bitmap getimage(String srcPath) {
162 | BitmapFactory.Options newOpts = new BitmapFactory.Options();
163 | //开始读入图片,此时把options.inJustDecodeBounds 设回true了
164 | newOpts.inJustDecodeBounds = true;
165 | Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空
166 |
167 | newOpts.inJustDecodeBounds = false;
168 | int w = newOpts.outWidth;
169 | int h = newOpts.outHeight;
170 | //现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
171 | float hh = 800f;//这里设置高度为800f
172 | float ww = 480f;//这里设置宽度为480f
173 | //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
174 | int be = 1;//be=1表示不缩放
175 | if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
176 | be = (int) (newOpts.outWidth / ww);
177 | } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
178 | be = (int) (newOpts.outHeight / hh);
179 | }
180 | if (be <= 0)
181 | be = 1;
182 | newOpts.inSampleSize = be;//设置缩放比例
183 | //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
184 | bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
185 | return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
186 | }
187 |
188 | /**
189 | * 图片按比例大小压缩方法(根据Bitmap图片压缩)
190 | * @param image
191 | * @return
192 | */
193 | public static Bitmap comp(Bitmap image) {
194 |
195 | ByteArrayOutputStream baos = new ByteArrayOutputStream();
196 | image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
197 | if( baos.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
198 | baos.reset();//重置baos即清空baos
199 | image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%,把压缩后的数据存放到baos中
200 | }
201 | ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
202 | BitmapFactory.Options newOpts = new BitmapFactory.Options();
203 | //开始读入图片,此时把options.inJustDecodeBounds 设回true了
204 | newOpts.inJustDecodeBounds = true;
205 | Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
206 | newOpts.inJustDecodeBounds = false;
207 | int w = newOpts.outWidth;
208 | int h = newOpts.outHeight;
209 | //现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
210 | float hh = 800f;//这里设置高度为800f
211 | float ww = 480f;//这里设置宽度为480f
212 | //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
213 | int be = 1;//be=1表示不缩放
214 | if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
215 | be = (int) (newOpts.outWidth / ww);
216 | } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
217 | be = (int) (newOpts.outHeight / hh);
218 | }
219 | if (be <= 0)
220 | be = 1;
221 | newOpts.inSampleSize = be;//设置缩放比例
222 | //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
223 | isBm = new ByteArrayInputStream(baos.toByteArray());
224 | bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
225 | return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
226 | }
227 | public static Bitmap zoomBitmap(Bitmap bitmap,float scale){
228 | int width = bitmap.getWidth();
229 | int height = bitmap.getHeight();
230 | Log.e("ss","width="+width);
231 | Log.e("ss","height="+height);
232 | Matrix matrix = new Matrix();
233 | //float scaleWidht = ((float)w / width);
234 | //float scaleHeight = ((float)h / height);
235 | matrix.postScale(scale, scale);
236 | Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
237 | return newbmp;
238 | }
239 |
240 | /**
241 | * 计算缩略图压缩的比列,因为每张图片长宽不一样,压缩比列也不一样
242 | *
243 | * @param options
244 | * @param reqWidth
245 | * @param reqHeight
246 | * @return
247 | */
248 | public static int calculateInSampleSize(BitmapFactory.Options options,
249 | int reqWidth, int reqHeight) {
250 | // Raw height and width of image
251 | final int height = options.outHeight;
252 | final int width = options.outWidth;
253 | int inSampleSize = 1;
254 | if (height > reqHeight || width > reqWidth) {
255 | if (width > height) {
256 | inSampleSize = Math.round((float) height / (float) reqHeight);
257 | } else {
258 | inSampleSize = Math.round((float) width / (float) reqWidth);
259 | }
260 | }
261 | return inSampleSize;
262 | }
263 |
264 | /**
265 | * @param bm
266 | * @return
267 | */
268 | public byte[] Bitmap2Bytes(Bitmap bm) {
269 | if (bm == null) {
270 | return null;
271 | }
272 | ByteArrayOutputStream baos = new ByteArrayOutputStream();
273 | bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
274 | return baos.toByteArray();
275 | }
276 |
277 | public Bitmap getBitmapFromView(View view) {
278 | view.destroyDrawingCache();
279 | view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
280 | View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
281 | view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
282 | view.setDrawingCacheEnabled(true);
283 | Bitmap bitmap = view.getDrawingCache(true);
284 | return bitmap;
285 | }
286 |
287 | //将Drawable转化为Bitmap
288 | public Bitmap drawableToBitmap(Drawable drawable) {
289 | int width = drawable.getIntrinsicWidth();
290 | int height = drawable.getIntrinsicHeight();
291 | Bitmap bitmap = Bitmap.createBitmap(width, height,
292 | drawable.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888
293 | : Config.RGB_565);
294 | Canvas canvas = new Canvas(bitmap);
295 | drawable.setBounds(0, 0, width, height);
296 | drawable.draw(canvas);
297 | return bitmap;
298 | }
299 |
300 | //获得圆角图片的方法
301 | public Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
302 |
303 | Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
304 | .getHeight(), Config.ARGB_8888);
305 | Canvas canvas = new Canvas(output);
306 |
307 | final int color = 0xff424242;
308 | final Paint paint = new Paint();
309 | final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
310 | final RectF rectF = new RectF(rect);
311 |
312 | paint.setAntiAlias(true);
313 | canvas.drawARGB(0, 0, 0, 0);
314 | paint.setColor(color);
315 | canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
316 |
317 | paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
318 | canvas.drawBitmap(bitmap, rect, rect, paint);
319 |
320 | return output;
321 | }
322 |
323 | //获得带阴影的图片方法
324 | public Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
325 | final int reflectionGap = 4;
326 | int width = bitmap.getWidth();
327 | int height = bitmap.getHeight();
328 |
329 | Matrix matrix = new Matrix();
330 | matrix.preScale(1, -1);
331 |
332 | Bitmap reflectionImage = Bitmap.createBitmap(bitmap,
333 | 0, height / 2, width, height / 2, matrix, false);
334 |
335 | Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888);
336 |
337 | Canvas canvas = new Canvas(bitmapWithReflection);
338 | canvas.drawBitmap(bitmap, 0, 0, null);
339 | Paint deafalutPaint = new Paint();
340 | canvas.drawRect(0, height, width, height + reflectionGap,
341 | deafalutPaint);
342 |
343 | canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
344 |
345 | Paint paint = new Paint();
346 | LinearGradient shader = new LinearGradient(0,
347 | bitmap.getHeight(), 0, bitmapWithReflection.getHeight()
348 | + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);
349 | paint.setShader(shader);
350 | // Set the Transfer mode to be porter duff and destination in
351 | paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
352 | // Draw a rectangle using the paint with our linear gradient
353 | canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
354 | + reflectionGap, paint);
355 |
356 | return bitmapWithReflection;
357 | }
358 |
359 | }
360 |
361 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/java/com/test/poiword/utils/ListUtils.java:
--------------------------------------------------------------------------------
1 | package com.test.poiword.utils;
2 |
3 | import android.text.TextUtils;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | /**
9 | * List Utils
10 | *
11 | * @author fuweiwei 2015-9-2
12 | */
13 | public class ListUtils {
14 |
15 | /** default join separator **/
16 | public static final String DEFAULT_JOIN_SEPARATOR = ",";
17 |
18 | private ListUtils() {
19 | throw new AssertionError();
20 | }
21 |
22 | /**
23 | * get size of list
24 | *
25 | *
26 | * getSize(null) = 0;
27 | * getSize({}) = 0;
28 | * getSize({1}) = 1;
29 | *
30 | *
31 | * @param
32 | * @param sourceList
33 | * @return if list is null or empty, return 0, else return {@link List#size()}.
34 | */
35 | public static int getSize(List sourceList) {
36 | return sourceList == null ? 0 : sourceList.size();
37 | }
38 |
39 | /**
40 | * is null or its size is 0
41 | *
42 | *
43 | * isEmpty(null) = true;
44 | * isEmpty({}) = true;
45 | * isEmpty({1}) = false;
46 | *
47 | *
48 | * @param
49 | * @param sourceList
50 | * @return if list is null or its size is 0, return true, else return false.
51 | */
52 | public static boolean isEmpty(List sourceList) {
53 | return (sourceList == null || sourceList.size() == 0);
54 | }
55 |
56 | /**
57 | * compare two list
58 | *
59 | *
60 | * isEquals(null, null) = true;
61 | * isEquals(new ArrayList<String>(), null) = false;
62 | * isEquals(null, new ArrayList<String>()) = false;
63 | * isEquals(new ArrayList<String>(), new ArrayList<String>()) = true;
64 | *
65 | *
66 | * @param
67 | * @param actual
68 | * @param expected
69 | * @return
70 | */
71 | public static boolean isEquals(ArrayList actual, ArrayList expected) {
72 | if (actual == null) {
73 | return expected == null;
74 | }
75 | if (expected == null) {
76 | return false;
77 | }
78 | if (actual.size() != expected.size()) {
79 | return false;
80 | }
81 |
82 | for (int i = 0; i < actual.size(); i++) {
83 | if (!ObjectUtils.isEquals(actual.get(i), expected.get(i))) {
84 | return false;
85 | }
86 | }
87 | return true;
88 | }
89 |
90 | /**
91 | * join list to string, separator is ","
92 | *
93 | *
94 | * join(null) = "";
95 | * join({}) = "";
96 | * join({a,b}) = "a,b";
97 | *
98 | *
99 | * @param list
100 | * @return join list to string, separator is ",". if list is empty, return ""
101 | */
102 | public static String join(List list) {
103 | return join(list, DEFAULT_JOIN_SEPARATOR);
104 | }
105 |
106 | /**
107 | * join list to string
108 | *
109 | *
110 | * join(null, '#') = "";
111 | * join({}, '#') = "";
112 | * join({a,b,c}, ' ') = "abc";
113 | * join({a,b,c}, '#') = "a#b#c";
114 | *
115 | *
116 | * @param list
117 | * @param separator
118 | * @return join list to string. if list is empty, return ""
119 | */
120 | public static String join(List list, char separator) {
121 | return join(list, new String(new char[] {separator}));
122 | }
123 |
124 | /**
125 | * join list to string. if separator is null, use {@link #DEFAULT_JOIN_SEPARATOR}
126 | *
127 | *
128 | * join(null, "#") = "";
129 | * join({}, "#$") = "";
130 | * join({a,b,c}, null) = "a,b,c";
131 | * join({a,b,c}, "") = "abc";
132 | * join({a,b,c}, "#") = "a#b#c";
133 | * join({a,b,c}, "#$") = "a#$b#$c";
134 | *
135 | *
136 | * @param list
137 | * @param separator
138 | * @return join list to string with separator. if list is empty, return ""
139 | */
140 | public static String join(List list, String separator) {
141 | return list == null ? "" : TextUtils.join(separator, list);
142 | }
143 |
144 | /**
145 | * add distinct entry to list
146 | *
147 | * @param
148 | * @param sourceList
149 | * @param entry
150 | * @return if entry already exist in sourceList, return false, else add it and return true.
151 | */
152 | public static boolean addDistinctEntry(List sourceList, V entry) {
153 | return (sourceList != null && !sourceList.contains(entry)) ? sourceList.add(entry) : false;
154 | }
155 |
156 | /**
157 | * add all distinct entry to list1 from list2
158 | *
159 | * @param
160 | * @param sourceList
161 | * @param entryList
162 | * @return the count of entries be added
163 | */
164 | public static int addDistinctList(List sourceList, List entryList) {
165 | if (sourceList == null || isEmpty(entryList)) {
166 | return 0;
167 | }
168 |
169 | int sourceCount = sourceList.size();
170 | for (V entry : entryList) {
171 | if (!sourceList.contains(entry)) {
172 | sourceList.add(entry);
173 | }
174 | }
175 | return sourceList.size() - sourceCount;
176 | }
177 |
178 | /**
179 | * remove duplicate entries in list
180 | *
181 | * @param
182 | * @param sourceList
183 | * @return the count of entries be removed
184 | */
185 | public static int distinctList(List sourceList) {
186 | if (isEmpty(sourceList)) {
187 | return 0;
188 | }
189 |
190 | int sourceCount = sourceList.size();
191 | int sourceListSize = sourceList.size();
192 | for (int i = 0; i < sourceListSize; i++) {
193 | for (int j = (i + 1); j < sourceListSize; j++) {
194 | if (sourceList.get(i).equals(sourceList.get(j))) {
195 | sourceList.remove(j);
196 | sourceListSize = sourceList.size();
197 | j--;
198 | }
199 | }
200 | }
201 | return sourceCount - sourceList.size();
202 | }
203 |
204 | /**
205 | * add not null entry to list
206 | *
207 | * @param sourceList
208 | * @param value
209 | * @return
210 | * - if sourceList is null, return false
211 | * - if value is null, return false
212 | * - return {@link List#add(Object)}
213 | *
214 | */
215 | public static boolean addListNotNullValue(List sourceList, V value) {
216 | return (sourceList != null && value != null) ? sourceList.add(value) : false;
217 | }
218 |
219 |
220 | /**
221 | * invert list
222 | *
223 | * @param
224 | * @param sourceList
225 | * @return
226 | */
227 | public static List invertList(List sourceList) {
228 | if (isEmpty(sourceList)) {
229 | return sourceList;
230 | }
231 |
232 | List invertList = new ArrayList(sourceList.size());
233 | for (int i = sourceList.size() - 1; i >= 0; i--) {
234 | invertList.add(sourceList.get(i));
235 | }
236 | return invertList;
237 | }
238 | }
239 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/java/com/test/poiword/utils/ObjectUtils.java:
--------------------------------------------------------------------------------
1 | package com.test.poiword.utils;
2 |
3 | import android.content.ContentValues;
4 | import android.util.Log;
5 |
6 | import java.lang.reflect.Field;
7 | import java.lang.reflect.Method;
8 |
9 | /**
10 | * Object Utils
11 | *
12 | * @author fuweiwei 2015-9-2
13 | */
14 | public class ObjectUtils {
15 |
16 | private ObjectUtils() {
17 | throw new AssertionError();
18 | }
19 |
20 | /**
21 | * compare two object
22 | *
23 | * @param actual
24 | * @param expected
25 | * @return
26 | * - if both are null, return true
27 | * - return actual.{@link Object#equals(Object)}
28 | *
29 | */
30 | public static boolean isEquals(Object actual, Object expected) {
31 | return actual == expected || (actual == null ? expected == null : actual.equals(expected));
32 | }
33 |
34 | /**
35 | * null Object to empty string
36 | *
37 | *
38 | * nullStrToEmpty(null) = "";
39 | * nullStrToEmpty("") = "";
40 | * nullStrToEmpty("aa") = "aa";
41 | *
42 | *
43 | * @param str
44 | * @return
45 | */
46 | public static String nullStrToEmpty(Object str) {
47 | return (str == null ? "" : (str instanceof String ? (String)str : str.toString()));
48 | }
49 |
50 | /**
51 | * convert long array to Long array
52 | *
53 | * @param source
54 | * @return
55 | */
56 | public static Long[] transformLongArray(long[] source) {
57 | Long[] destin = new Long[source.length];
58 | for (int i = 0; i < source.length; i++) {
59 | destin[i] = source[i];
60 | }
61 | return destin;
62 | }
63 |
64 | /**
65 | * convert Long array to long array
66 | *
67 | * @param source
68 | * @return
69 | */
70 | public static long[] transformLongArray(Long[] source) {
71 | long[] destin = new long[source.length];
72 | for (int i = 0; i < source.length; i++) {
73 | destin[i] = source[i];
74 | }
75 | return destin;
76 | }
77 |
78 | /**
79 | * convert int array to Integer array
80 | *
81 | * @param source
82 | * @return
83 | */
84 | public static Integer[] transformIntArray(int[] source) {
85 | Integer[] destin = new Integer[source.length];
86 | for (int i = 0; i < source.length; i++) {
87 | destin[i] = source[i];
88 | }
89 | return destin;
90 | }
91 |
92 | /**
93 | * convert Integer array to int array
94 | *
95 | * @param source
96 | * @return
97 | */
98 | public static int[] transformIntArray(Integer[] source) {
99 | int[] destin = new int[source.length];
100 | for (int i = 0; i < source.length; i++) {
101 | destin[i] = source[i];
102 | }
103 | return destin;
104 | }
105 |
106 | /**
107 | * compare two object
108 | *
109 | * About result
110 | * - if v1 > v2, return 1
111 | * - if v1 = v2, return 0
112 | * - if v1 < v2, return -1
113 | *
114 | *
115 | * About rule
116 | * - if v1 is null, v2 is null, then return 0
117 | * - if v1 is null, v2 is not null, then return -1
118 | * - if v1 is not null, v2 is null, then return 1
119 | * - return v1.{@link Comparable#compareTo(Object)}
120 | *
121 | *
122 | * @param v1
123 | * @param v2
124 | * @return
125 | */
126 | @SuppressWarnings({"unchecked", "rawtypes"})
127 | public static int compare(V v1, V v2) {
128 | return v1 == null ? (v2 == null ? 0 : -1) : (v2 == null ? 1 : ((Comparable)v1).compareTo(v2));
129 | }
130 |
131 | /**
132 | * 获取对象属性,返回一个字符串数组
133 | * @param o 对象
134 | * @return ContentValues
135 | */
136 | public static ContentValues getContentValues(Object o) {
137 | try {
138 | Field[] fields = o.getClass().getDeclaredFields();
139 | String[] fieldNames = new String[fields.length];
140 | ContentValues values = new ContentValues();
141 | for (int i = 0; i < fields.length; i++) {
142 | String key = fields[i].getName();
143 | Object value = getFieldValueByName(key, o);
144 | values.put(fields[i].getName(), value.toString());
145 | }
146 | return values;
147 | } catch (SecurityException e) {
148 | e.printStackTrace();
149 | }
150 | return null;
151 | }
152 |
153 | /**
154 | * 使用反射根据属性名称获取属性值
155 | * @param fieldName 属性名称
156 | * @param o 操作对象
157 | * @return Object 属性值
158 | */
159 |
160 | public static Object getFieldValueByName(String fieldName, Object o) {
161 | try {
162 | String firstLetter = fieldName.substring(0, 1).toUpperCase();
163 | String getter = "get" + firstLetter + fieldName.substring(1);
164 | Method method = o.getClass().getMethod(getter, new Class[]{});
165 | Object value = method.invoke(o, new Object[]{});
166 | return value;
167 | } catch (Exception e) {
168 | Log.e("error", "属性名不存在");
169 | return null;
170 | }
171 | }
172 | }
173 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/java/com/test/poiword/utils/PreferencesUtils.java:
--------------------------------------------------------------------------------
1 | package com.test.poiword.utils;
2 |
3 | import android.content.Context;
4 | import android.content.SharedPreferences;
5 |
6 | /**
7 | * PreferencesUtils, easy to get or put data
8 | *
9 | * Preference Name
10 | * - you can change preference name by {@link #PREFERENCE_NAME}
11 | *
12 | *
13 | * Put Value
14 | * - put string {@link #putString(Context, String, String)}
15 | * - put int {@link #putInt(Context, String, int)}
16 | * - put long {@link #putLong(Context, String, long)}
17 | * - put float {@link #putFloat(Context, String, float)}
18 | * - put boolean {@link #putBoolean(Context, String, boolean)}
19 | *
20 | *
21 | * Get Value
22 | * - get string {@link #getString(Context, String)}, {@link #getString(Context, String, String)}
23 | * - get int {@link #getInt(Context, String)}, {@link #getInt(Context, String, int)}
24 | * - get long {@link #getLong(Context, String)}, {@link #getLong(Context, String, long)}
25 | * - get float {@link #getFloat(Context, String)}, {@link #getFloat(Context, String, float)}
26 | * - get boolean {@link #getBoolean(Context, String)}, {@link #getBoolean(Context, String, boolean)}
27 | *
28 | *
29 | * @author fuweiwei 2015-9-2
30 | */
31 | public class PreferencesUtils {
32 |
33 | public static String PREFERENCE_NAME = "HighWaySystem";
34 |
35 | private PreferencesUtils() {
36 | throw new AssertionError();
37 | }
38 |
39 | /**
40 | * put string preferences
41 | *
42 | * @param context
43 | * @param key The name of the preference to modify
44 | * @param value The new value for the preference
45 | * @return True if the new values were successfully written to persistent storage.
46 | */
47 | public static boolean putString(Context context, String key, String value) {
48 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
49 | SharedPreferences.Editor editor = settings.edit();
50 | editor.putString(key, value);
51 | return editor.commit();
52 | }
53 |
54 | /**
55 | * get string preferences
56 | *
57 | * @param context
58 | * @param key The name of the preference to retrieve
59 | * @return The preference value if it exists, or null. Throws ClassCastException if there is a preference with this
60 | * name that is not a string
61 | * @see #getString(Context, String, String)
62 | */
63 | public static String getString(Context context, String key) {
64 | return getString(context, key, null);
65 | }
66 |
67 | /**
68 | * get string preferences
69 | *
70 | * @param context
71 | * @param key The name of the preference to retrieve
72 | * @param defaultValue Value to return if this preference does not exist
73 | * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
74 | * this name that is not a string
75 | */
76 | public static String getString(Context context, String key, String defaultValue) {
77 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
78 | return settings.getString(key, defaultValue);
79 | }
80 |
81 | /**
82 | * put int preferences
83 | *
84 | * @param context
85 | * @param key The name of the preference to modify
86 | * @param value The new value for the preference
87 | * @return True if the new values were successfully written to persistent storage.
88 | */
89 | public static boolean putInt(Context context, String key, int value) {
90 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
91 | SharedPreferences.Editor editor = settings.edit();
92 | editor.putInt(key, value);
93 | return editor.commit();
94 | }
95 |
96 | /**
97 | * get int preferences
98 | *
99 | * @param context
100 | * @param key The name of the preference to retrieve
101 | * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this
102 | * name that is not a int
103 | * @see #getInt(Context, String, int)
104 | */
105 | public static int getInt(Context context, String key) {
106 | return getInt(context, key, -1);
107 | }
108 |
109 | /**
110 | * get int preferences
111 | *
112 | * @param context
113 | * @param key The name of the preference to retrieve
114 | * @param defaultValue Value to return if this preference does not exist
115 | * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
116 | * this name that is not a int
117 | */
118 | public static int getInt(Context context, String key, int defaultValue) {
119 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
120 | return settings.getInt(key, defaultValue);
121 | }
122 |
123 | /**
124 | * put long preferences
125 | *
126 | * @param context
127 | * @param key The name of the preference to modify
128 | * @param value The new value for the preference
129 | * @return True if the new values were successfully written to persistent storage.
130 | */
131 | public static boolean putLong(Context context, String key, long value) {
132 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
133 | SharedPreferences.Editor editor = settings.edit();
134 | editor.putLong(key, value);
135 | return editor.commit();
136 | }
137 |
138 | /**
139 | * get long preferences
140 | *
141 | * @param context
142 | * @param key The name of the preference to retrieve
143 | * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this
144 | * name that is not a long
145 | * @see #getLong(Context, String, long)
146 | */
147 | public static long getLong(Context context, String key) {
148 | return getLong(context, key, -1);
149 | }
150 |
151 | /**
152 | * get long preferences
153 | *
154 | * @param context
155 | * @param key The name of the preference to retrieve
156 | * @param defaultValue Value to return if this preference does not exist
157 | * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
158 | * this name that is not a long
159 | */
160 | public static long getLong(Context context, String key, long defaultValue) {
161 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
162 | return settings.getLong(key, defaultValue);
163 | }
164 |
165 | /**
166 | * put float preferences
167 | *
168 | * @param context
169 | * @param key The name of the preference to modify
170 | * @param value The new value for the preference
171 | * @return True if the new values were successfully written to persistent storage.
172 | */
173 | public static boolean putFloat(Context context, String key, float value) {
174 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
175 | SharedPreferences.Editor editor = settings.edit();
176 | editor.putFloat(key, value);
177 | return editor.commit();
178 | }
179 |
180 | /**
181 | * get float preferences
182 | *
183 | * @param context
184 | * @param key The name of the preference to retrieve
185 | * @return The preference value if it exists, or -1. Throws ClassCastException if there is a preference with this
186 | * name that is not a float
187 | * @see #getFloat(Context, String, float)
188 | */
189 | public static float getFloat(Context context, String key) {
190 | return getFloat(context, key, -1);
191 | }
192 |
193 | /**
194 | * get float preferences
195 | *
196 | * @param context
197 | * @param key The name of the preference to retrieve
198 | * @param defaultValue Value to return if this preference does not exist
199 | * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
200 | * this name that is not a float
201 | */
202 | public static float getFloat(Context context, String key, float defaultValue) {
203 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
204 | return settings.getFloat(key, defaultValue);
205 | }
206 |
207 | /**
208 | * put boolean preferences
209 | *
210 | * @param context
211 | * @param key The name of the preference to modify
212 | * @param value The new value for the preference
213 | * @return True if the new values were successfully written to persistent storage.
214 | */
215 | public static boolean putBoolean(Context context, String key, boolean value) {
216 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
217 | SharedPreferences.Editor editor = settings.edit();
218 | editor.putBoolean(key, value);
219 | return editor.commit();
220 | }
221 |
222 | /**
223 | * get boolean preferences, default is false
224 | *
225 | * @param context
226 | * @param key The name of the preference to retrieve
227 | * @return The preference value if it exists, or false. Throws ClassCastException if there is a preference with this
228 | * name that is not a boolean
229 | * @see #getBoolean(Context, String, boolean)
230 | */
231 | public static boolean getBoolean(Context context, String key) {
232 | return getBoolean(context, key, false);
233 | }
234 |
235 | /**
236 | * get boolean preferences
237 | *
238 | * @param context
239 | * @param key The name of the preference to retrieve
240 | * @param defaultValue Value to return if this preference does not exist
241 | * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
242 | * this name that is not a boolean
243 | */
244 | public static boolean getBoolean(Context context, String key, boolean defaultValue) {
245 | SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
246 | return settings.getBoolean(key, defaultValue);
247 | }
248 | }
249 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/java/com/test/poiword/utils/ScreenUtils.java:
--------------------------------------------------------------------------------
1 | package com.test.poiword.utils;
2 |
3 | import android.content.Context;
4 | import android.view.WindowManager;
5 |
6 | /**
7 | * ScreenUtils
8 | *
9 | * Convert between dp and sp
10 | * - {@link ScreenUtils#dpToPx(Context, float)}
11 | * - {@link ScreenUtils#pxToDp(Context, float)}
12 | *
13 | *
14 | * @author fuweiwei 2015-9-2
15 | */
16 | public class ScreenUtils {
17 |
18 | private ScreenUtils() {
19 | throw new AssertionError();
20 | }
21 |
22 | public static float dpToPx(Context context, float dp) {
23 | if (context == null) {
24 | return -1;
25 | }
26 | return dp * context.getResources().getDisplayMetrics().density;
27 | }
28 |
29 | public static float pxToDp(Context context, float px) {
30 | if (context == null) {
31 | return -1;
32 | }
33 | return px / context.getResources().getDisplayMetrics().density;
34 | }
35 |
36 | public static int dpToPxInt(Context context, float dp) {
37 | return (int)(dpToPx(context, dp) + 0.5f);
38 | }
39 |
40 | public static int pxToDpCeilInt(Context context, float px) {
41 | return (int)(pxToDp(context, px) + 0.5f);
42 | }
43 | /**
44 | *
45 | * @Title: getScreenWidth
46 | * @Description: TODO(获取屏幕宽度)
47 | */
48 | public static int getScreenWidth(Context context){
49 |
50 | WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
51 | return wm.getDefaultDisplay().getWidth();
52 |
53 | }
54 | /**
55 | *
56 | * @Title: getScreenHeight
57 | * @Description: TODO(获取屏幕高度)
58 | */
59 | public static int getScreenHeight(Context context){
60 |
61 | WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
62 | return wm.getDefaultDisplay().getHeight();
63 |
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/java/com/test/poiword/utils/StringUtils.java:
--------------------------------------------------------------------------------
1 | package com.test.poiword.utils;
2 |
3 | import java.io.UnsupportedEncodingException;
4 | import java.net.URLEncoder;
5 | import java.util.regex.Matcher;
6 | import java.util.regex.Pattern;
7 |
8 | /**
9 | * String Utils
10 | *
11 | * @author fuweiwei 2015-9-2
12 | */
13 | public class StringUtils {
14 |
15 | private StringUtils() {
16 | throw new AssertionError();
17 | }
18 |
19 | /**
20 | * is null or its length is 0 or it is made by space
21 | *
22 | *
23 | * isBlank(null) = true;
24 | * isBlank("") = true;
25 | * isBlank(" ") = true;
26 | * isBlank("a") = false;
27 | * isBlank("a ") = false;
28 | * isBlank(" a") = false;
29 | * isBlank("a b") = false;
30 | *
31 | *
32 | * @param str
33 | * @return if string is null or its size is 0 or it is made by space, return true, else return false.
34 | */
35 | public static boolean isBlank(String str) {
36 | return (str == null || str.trim().length() == 0);
37 | }
38 |
39 | /**
40 | * is null or its length is 0
41 | *
42 | *
43 | * isEmpty(null) = true;
44 | * isEmpty("") = true;
45 | * isEmpty(" ") = false;
46 | *
47 | *
48 | * @param str
49 | * @return if string is null or its size is 0, return true, else return false.
50 | */
51 | public static boolean isEmpty(CharSequence str) {
52 | return (str == null || str.length() == 0);
53 | }
54 |
55 | /**
56 | * compare two string
57 | *
58 | * @param actual
59 | * @param expected
60 | * @return
61 | * @see ObjectUtils#isEquals(Object, Object)
62 | */
63 | public static boolean isEquals(String actual, String expected) {
64 | return ObjectUtils.isEquals(actual, expected);
65 | }
66 |
67 | /**
68 | * get length of CharSequence
69 | *
70 | *
71 | * length(null) = 0;
72 | * length(\"\") = 0;
73 | * length(\"abc\") = 3;
74 | *
75 | *
76 | * @param str
77 | * @return if str is null or empty, return 0, else return {@link CharSequence#length()}.
78 | */
79 | public static int length(CharSequence str) {
80 | return str == null ? 0 : str.length();
81 | }
82 |
83 | /**
84 | * null Object to empty string
85 | *
86 | *
87 | * nullStrToEmpty(null) = "";
88 | * nullStrToEmpty("") = "";
89 | * nullStrToEmpty("aa") = "aa";
90 | *
91 | *
92 | * @param str
93 | * @return
94 | */
95 | public static String nullStrToEmpty(Object str) {
96 | return (str == null ? "" : (str instanceof String ? (String)str : str.toString()));
97 | }
98 |
99 | /**
100 | * capitalize first letter
101 | *
102 | *
103 | * capitalizeFirstLetter(null) = null;
104 | * capitalizeFirstLetter("") = "";
105 | * capitalizeFirstLetter("2ab") = "2ab"
106 | * capitalizeFirstLetter("a") = "A"
107 | * capitalizeFirstLetter("ab") = "Ab"
108 | * capitalizeFirstLetter("Abc") = "Abc"
109 | *
110 | *
111 | * @param str
112 | * @return
113 | */
114 | public static String capitalizeFirstLetter(String str) {
115 | if (isEmpty(str)) {
116 | return str;
117 | }
118 |
119 | char c = str.charAt(0);
120 | return (!Character.isLetter(c) || Character.isUpperCase(c)) ? str : new StringBuilder(str.length())
121 | .append(Character.toUpperCase(c)).append(str.substring(1)).toString();
122 | }
123 |
124 | /**
125 | * encoded in utf-8
126 | *
127 | *
128 | * utf8Encode(null) = null
129 | * utf8Encode("") = "";
130 | * utf8Encode("aa") = "aa";
131 | * utf8Encode("啊啊啊啊") = "%E5%95%8A%E5%95%8A%E5%95%8A%E5%95%8A";
132 | *
133 | *
134 | * @param str
135 | * @return
136 | * @throws UnsupportedEncodingException if an error occurs
137 | */
138 | public static String utf8Encode(String str) {
139 | if (!isEmpty(str) && str.getBytes().length != str.length()) {
140 | try {
141 | return URLEncoder.encode(str, "UTF-8");
142 | } catch (UnsupportedEncodingException e) {
143 | throw new RuntimeException("UnsupportedEncodingException occurred. ", e);
144 | }
145 | }
146 | return str;
147 | }
148 |
149 | /**
150 | * encoded in utf-8, if exception, return defultReturn
151 | *
152 | * @param str
153 | * @param defultReturn
154 | * @return
155 | */
156 | public static String utf8Encode(String str, String defultReturn) {
157 | if (!isEmpty(str) && str.getBytes().length != str.length()) {
158 | try {
159 | return URLEncoder.encode(str, "UTF-8");
160 | } catch (UnsupportedEncodingException e) {
161 | return defultReturn;
162 | }
163 | }
164 | return str;
165 | }
166 |
167 | /**
168 | * get innerHtml from href
169 | *
170 | *
171 | * getHrefInnerHtml(null) = ""
172 | * getHrefInnerHtml("") = ""
173 | * getHrefInnerHtml("mp3") = "mp3";
174 | * getHrefInnerHtml("<a innerHtml</a>") = "<a innerHtml</a>";
175 | * getHrefInnerHtml("<a>innerHtml</a>") = "innerHtml";
176 | * getHrefInnerHtml("<a<a>innerHtml</a>") = "innerHtml";
177 | * getHrefInnerHtml("<a href="baidu.com">innerHtml</a>") = "innerHtml";
178 | * getHrefInnerHtml("<a href="baidu.com" title="baidu">innerHtml</a>") = "innerHtml";
179 | * getHrefInnerHtml(" <a>innerHtml</a> ") = "innerHtml";
180 | * getHrefInnerHtml("<a>innerHtml</a></a>") = "innerHtml";
181 | * getHrefInnerHtml("jack<a>innerHtml</a></a>") = "innerHtml";
182 | * getHrefInnerHtml("<a>innerHtml1</a><a>innerHtml2</a>") = "innerHtml2";
183 | *
184 | *
185 | * @param href
186 | * @return
187 | * - if href is null, return ""
188 | * - if not match regx, return source
189 | * - return the last string that match regx
190 | *
191 | */
192 | public static String getHrefInnerHtml(String href) {
193 | if (isEmpty(href)) {
194 | return "";
195 | }
196 |
197 | String hrefReg = ".*<[\\s]*a[\\s]*.*>(.+?)<[\\s]*/a[\\s]*>.*";
198 | Pattern hrefPattern = Pattern.compile(hrefReg, Pattern.CASE_INSENSITIVE);
199 | Matcher hrefMatcher = hrefPattern.matcher(href);
200 | if (hrefMatcher.matches()) {
201 | return hrefMatcher.group(1);
202 | }
203 | return href;
204 | }
205 |
206 | /**
207 | * process special char in html
208 | *
209 | *
210 | * htmlEscapeCharsToString(null) = null;
211 | * htmlEscapeCharsToString("") = "";
212 | * htmlEscapeCharsToString("mp3") = "mp3";
213 | * htmlEscapeCharsToString("mp3<") = "mp3<";
214 | * htmlEscapeCharsToString("mp3>") = "mp3\>";
215 | * htmlEscapeCharsToString("mp3&mp4") = "mp3&mp4";
216 | * htmlEscapeCharsToString("mp3"mp4") = "mp3\"mp4";
217 | * htmlEscapeCharsToString("mp3<>&"mp4") = "mp3\<\>&\"mp4";
218 | *
219 | *
220 | * @param source
221 | * @return
222 | */
223 | public static String htmlEscapeCharsToString(String source) {
224 | return StringUtils.isEmpty(source) ? source : source.replaceAll("<", "<").replaceAll(">", ">")
225 | .replaceAll("&", "&").replaceAll(""", "\"");
226 | }
227 |
228 | /**
229 | * transform half width char to full width char
230 | *
231 | *
232 | * fullWidthToHalfWidth(null) = null;
233 | * fullWidthToHalfWidth("") = "";
234 | * fullWidthToHalfWidth(new String(new char[] {12288})) = " ";
235 | * fullWidthToHalfWidth("!"#$%&) = "!\"#$%&";
236 | *
237 | *
238 | * @param s
239 | * @return
240 | */
241 | public static String fullWidthToHalfWidth(String s) {
242 | if (isEmpty(s)) {
243 | return s;
244 | }
245 |
246 | char[] source = s.toCharArray();
247 | for (int i = 0; i < source.length; i++) {
248 | if (source[i] == 12288) {
249 | source[i] = ' ';
250 | // } else if (source[i] == 12290) {
251 | // source[i] = '.';
252 | } else if (source[i] >= 65281 && source[i] <= 65374) {
253 | source[i] = (char)(source[i] - 65248);
254 | } else {
255 | source[i] = source[i];
256 | }
257 | }
258 | return new String(source);
259 | }
260 |
261 | /**
262 | * transform full width char to half width char
263 | *
264 | *
265 | * halfWidthToFullWidth(null) = null;
266 | * halfWidthToFullWidth("") = "";
267 | * halfWidthToFullWidth(" ") = new String(new char[] {12288});
268 | * halfWidthToFullWidth("!\"#$%&) = "!"#$%&";
269 | *
270 | *
271 | * @param s
272 | * @return
273 | */
274 | public static String halfWidthToFullWidth(String s) {
275 | if (isEmpty(s)) {
276 | return s;
277 | }
278 |
279 | char[] source = s.toCharArray();
280 | for (int i = 0; i < source.length; i++) {
281 | if (source[i] == ' ') {
282 | source[i] = (char)12288;
283 | // } else if (source[i] == '.') {
284 | // source[i] = (char)12290;
285 | } else if (source[i] >= 33 && source[i] <= 126) {
286 | source[i] = (char)(source[i] + 65248);
287 | } else {
288 | source[i] = source[i];
289 | }
290 | }
291 | return new String(source);
292 | }
293 | }
294 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/java/com/test/poiword/utils/ToastUtils.java:
--------------------------------------------------------------------------------
1 | package com.test.poiword.utils;
2 |
3 | import android.content.Context;
4 | import android.widget.Toast;
5 |
6 | /**
7 | * ToastUtils
8 | *
9 | * @author fuweiwei 2015-9-2
10 | */
11 | public class ToastUtils {
12 |
13 | private ToastUtils() {
14 | throw new AssertionError();
15 | }
16 |
17 | public static void show(Context context, int resId) {
18 | show(context, context.getResources().getText(resId), Toast.LENGTH_SHORT);
19 | }
20 |
21 | public static void show(Context context, int resId, int duration) {
22 | show(context, context.getResources().getText(resId), duration);
23 | }
24 |
25 | public static void show(Context context, CharSequence text) {
26 | show(context, text, Toast.LENGTH_SHORT);
27 | }
28 |
29 | public static void show(Context context, CharSequence text, int duration) {
30 | Toast.makeText(context, text, duration).show();
31 | }
32 |
33 | public static void show(Context context, int resId, Object... args) {
34 | show(context, String.format(context.getResources().getString(resId), args), Toast.LENGTH_SHORT);
35 | }
36 |
37 | public static void show(Context context, String format, Object... args) {
38 | show(context, String.format(format, args), Toast.LENGTH_SHORT);
39 | }
40 |
41 | public static void show(Context context, int resId, int duration, Object... args) {
42 | show(context, String.format(context.getResources().getString(resId), args), duration);
43 | }
44 |
45 | public static void show(Context context, String format, int duration, Object... args) {
46 | show(context, String.format(format, args), duration);
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
13 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/res/layout/html.xml:
--------------------------------------------------------------------------------
1 |
5 |
6 |
14 |
15 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/res/menu/menu_main.xml:
--------------------------------------------------------------------------------
1 |
7 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fuweiwei/AndroidPoiWord/94fce054dce162191eb890409fa5051973018640/MyPoiWordDemo/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fuweiwei/AndroidPoiWord/94fce054dce162191eb890409fa5051973018640/MyPoiWordDemo/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fuweiwei/AndroidPoiWord/94fce054dce162191eb890409fa5051973018640/MyPoiWordDemo/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fuweiwei/AndroidPoiWord/94fce054dce162191eb890409fa5051973018640/MyPoiWordDemo/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | MyPoiWordDemo
3 |
4 | Hello world!
5 | Settings
6 |
7 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:1.2.3'
9 |
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | }
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | jcenter()
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/MyPoiWordDemo/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fuweiwei/AndroidPoiWord/94fce054dce162191eb890409fa5051973018640/MyPoiWordDemo/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/MyPoiWordDemo/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Apr 10 15:27:10 PDT 2013
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip
7 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/MyPoiWordDemo/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # MyPoiWordDemo
2 | Android 使用模板生成Word文档,支持手机直接查看word
3 |
4 | 最近在项目工作中,碰到一个很棘手的需求,说是要在手机端根据模板生成word文档,而且不借助第三方的软件可以查看word文档,一开始听这个需求差不多蒙了,这要怎么做,为什么不把生成word文档这个工作放在后台呢,抱怨归抱怨,但是面对需求只能硬着头皮做了,经过各种拷问度娘和谷哥,终于找了一个比较好用的方法。特此跟他家分享。
5 |
6 | Apache 公司推出的 Apache POI,我们来看下他的介绍:Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能。
7 | 废话少说开始编码,首先我们要下Apache POI的开发jar包,下载地址:http://poi.apache.org/download.html,这里推荐不要下最新版本的,因为一开始我用最新版本的会出一下莫名其妙的问题,后面换旧的版本就OK了。这里我用的是3.9的还是比较稳定的、
8 |
9 |
10 | 开发有2个包,有一点我就非常郁闷Apache居然没有提供api稳定,开发起来还是比较蛋疼的,可能是我自己没有找到把,如果有知道的筒子可以@我、嘿嘿。不过Apache还是提供了Demo大家可以参考。
11 | 详情见博客:http://blog.csdn.net/u011916937/article/details/50085441
12 |
--------------------------------------------------------------------------------