├── MyPoiWordDemo ├── .gitignore ├── .idea │ ├── .name │ ├── compiler.xml │ ├── copyright │ │ └── profiles_settings.xml │ ├── encodings.xml │ ├── gradle.xml │ ├── misc.xml │ ├── modules.xml │ ├── runConfigurations.xml │ └── vcs.xml ├── MyPoiWordDemo.iml ├── app │ ├── .gitignore │ ├── app.iml │ ├── build.gradle │ ├── libs │ │ ├── poi-3.9-20121203.jar │ │ └── poi-scratchpad-3.9-20121203.jar │ ├── proguard-rules.pro │ └── src │ │ ├── androidTest │ │ └── java │ │ │ └── com │ │ │ └── test │ │ │ └── poiword │ │ │ └── ApplicationTest.java │ │ └── main │ │ ├── AndroidManifest.xml │ │ ├── assets │ │ └── test.doc │ │ ├── java │ │ └── com │ │ │ └── test │ │ │ └── poiword │ │ │ ├── MainActivity.java │ │ │ ├── WordHtmlActivity.java │ │ │ └── utils │ │ │ ├── CommonUtils.java │ │ │ ├── CursorUtils.java │ │ │ ├── FileUtils.java │ │ │ ├── ImageUtils.java │ │ │ ├── ListUtils.java │ │ │ ├── ObjectUtils.java │ │ │ ├── PreferencesUtils.java │ │ │ ├── ScreenUtils.java │ │ │ ├── StringUtils.java │ │ │ └── ToastUtils.java │ │ └── res │ │ ├── layout │ │ ├── activity_main.xml │ │ └── html.xml │ │ ├── menu │ │ └── menu_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml ├── build.gradle ├── gradle.properties ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle └── README.md /MyPoiWordDemo/.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | /.idea/workspace.xml 4 | /.idea/libraries 5 | .DS_Store 6 | /build 7 | /captures 8 | -------------------------------------------------------------------------------- /MyPoiWordDemo/.idea/.name: -------------------------------------------------------------------------------- 1 | MyPoiWordDemo -------------------------------------------------------------------------------- /MyPoiWordDemo/.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /MyPoiWordDemo/.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /MyPoiWordDemo/.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /MyPoiWordDemo/.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 18 | -------------------------------------------------------------------------------- /MyPoiWordDemo/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 19 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 46 | 47 | 48 | 49 | 50 | 1.7 51 | 52 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /MyPoiWordDemo/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /MyPoiWordDemo/.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /MyPoiWordDemo/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /MyPoiWordDemo/MyPoiWordDemo.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /MyPoiWordDemo/app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /MyPoiWordDemo/app/app.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 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 | -------------------------------------------------------------------------------- /MyPoiWordDemo/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 23 5 | buildToolsVersion '22.0.1' 6 | defaultConfig { 7 | applicationId "com.test.poiword" 8 | minSdkVersion 14 9 | targetSdkVersion 23 10 | versionCode 1 11 | versionName "1.0" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | productFlavors { 20 | } 21 | packagingOptions { 22 | exclude 'META-INF/DEPENDENCIES.txt' 23 | exclude 'META-INF/LICENSE.txt' 24 | exclude 'META-INF/NOTICE.txt' 25 | exclude 'META-INF/NOTICE' 26 | exclude 'META-INF/LICENSE' 27 | exclude 'META-INF/DEPENDENCIES' 28 | exclude 'META-INF/notice.txt' 29 | exclude 'META-INF/license.txt' 30 | exclude 'META-INF/dependencies.txt' 31 | exclude 'META-INF/LGPL2.1' 32 | } 33 | } 34 | 35 | dependencies { 36 | compile fileTree(dir: 'libs', include: ['*.jar']) 37 | compile 'com.android.support:appcompat-v7:23.1.1' 38 | compile files('libs/poi-3.9-20121203.jar') 39 | compile files('libs/poi-scratchpad-3.9-20121203.jar') 40 | } 41 | -------------------------------------------------------------------------------- /MyPoiWordDemo/app/libs/poi-3.9-20121203.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuweiwei/AndroidPoiWord/94fce054dce162191eb890409fa5051973018640/MyPoiWordDemo/app/libs/poi-3.9-20121203.jar -------------------------------------------------------------------------------- /MyPoiWordDemo/app/libs/poi-scratchpad-3.9-20121203.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuweiwei/AndroidPoiWord/94fce054dce162191eb890409fa5051973018640/MyPoiWordDemo/app/libs/poi-scratchpad-3.9-20121203.jar -------------------------------------------------------------------------------- /MyPoiWordDemo/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in F:\android studio\Android SDK/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /MyPoiWordDemo/app/src/androidTest/java/com/test/poiword/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.test.poiword; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /MyPoiWordDemo/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 11 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /MyPoiWordDemo/app/src/main/assets/test.doc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fuweiwei/AndroidPoiWord/94fce054dce162191eb890409fa5051973018640/MyPoiWordDemo/app/src/main/assets/test.doc -------------------------------------------------------------------------------- /MyPoiWordDemo/app/src/main/java/com/test/poiword/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.test.poiword; 2 | 3 | import android.app.Activity; 4 | import android.content.ActivityNotFoundException; 5 | import android.content.Intent; 6 | import android.net.Uri; 7 | import android.os.Bundle; 8 | import android.view.View; 9 | import android.view.View.OnClickListener; 10 | import android.widget.Button; 11 | import android.widget.Toast; 12 | 13 | import com.test.poiword.utils.FileUtils; 14 | 15 | import org.apache.poi.hwpf.HWPFDocument; 16 | import org.apache.poi.hwpf.usermodel.Range; 17 | 18 | import java.io.ByteArrayOutputStream; 19 | import java.io.File; 20 | import java.io.FileInputStream; 21 | import java.io.FileOutputStream; 22 | import java.io.IOException; 23 | import java.io.InputStream; 24 | import java.util.HashMap; 25 | import java.util.Map; 26 | 27 | public class MainActivity extends Activity { 28 | // 模板文集地址 29 | private static final String demoPath = "/mnt/sdcard/doc/test.doc"; 30 | // 创建生成的文件地址 31 | private static final String newPath = "/mnt/sdcard/doc/testS.doc"; 32 | private Button btn,btns; 33 | @Override 34 | protected void onCreate(Bundle savedInstanceState) { 35 | super.onCreate(savedInstanceState); 36 | setContentView(R.layout.activity_main); 37 | btn=(Button)findViewById(R.id.btn); 38 | btns=(Button)findViewById(R.id.btns); 39 | btn.setOnClickListener(new OnClickListener() { 40 | 41 | @Override 42 | public void onClick(View arg0) { 43 | try { 44 | InputStream inputStream = getAssets().open("test.doc"); 45 | FileUtils.writeFile(new File(demoPath), inputStream); 46 | } catch (Exception e) { 47 | e.printStackTrace(); 48 | } 49 | doScan(); 50 | } 51 | }); 52 | btns.setOnClickListener(new OnClickListener() { 53 | 54 | @Override 55 | public void onClick(View arg0) { 56 | Intent intent = new Intent(MainActivity.this,WordHtmlActivity.class); 57 | startActivity(intent); 58 | } 59 | }); 60 | 61 | } 62 | 63 | private void doScan(){ 64 | //获取模板文件 65 | File demoFile=new File(demoPath); 66 | //创建生成的文件 67 | File newFile=new File(newPath); 68 | Map map = new HashMap(); 69 | map.put("$QYMC$", "xxx科技股份有限公司"); 70 | map.put("$QYDZ$", "上海市杨浦区xx路xx号"); 71 | map.put("$QYFZR$", "张三"); 72 | map.put("$FRDB$", "李四"); 73 | map.put("$CJSJ$", "2000-11-10"); 74 | map.put("$SCPZMSJWT$", "5"); 75 | map.put("$XCJCJBQ$", "6"); 76 | map.put("$JLJJJFF$", "7"); 77 | map.put("$QYFZRQM$", "张三"); 78 | map.put("$CPRWQM$", "赵六"); 79 | map.put("$ZFZH$", "100001"); 80 | map.put("$BZ$", "无"); 81 | writeDoc(demoFile,newFile,map); 82 | //查看 83 | doOpenWord(); 84 | } 85 | /** 86 | * 调用手机中安装的可打开word的软件 87 | */ 88 | private void doOpenWord(){ 89 | Intent intent = new Intent(); 90 | intent.setAction("android.intent.action.VIEW"); 91 | intent.addCategory("android.intent.category.DEFAULT"); 92 | String fileMimeType = "application/msword"; 93 | intent.setDataAndType(Uri.fromFile(new File(newPath)), fileMimeType); 94 | try{ 95 | MainActivity.this.startActivity(intent); 96 | } catch(ActivityNotFoundException e) { 97 | //检测到系统尚未安装OliveOffice的apk程序 98 | Toast.makeText(MainActivity.this, "未找到软件", Toast.LENGTH_LONG).show(); 99 | //请先到www.olivephone.com/e.apk下载并安装 100 | } 101 | } 102 | /** 103 | * demoFile 模板文件 104 | * newFile 生成文件 105 | * map 要填充的数据 106 | * */ 107 | public void writeDoc(File demoFile ,File newFile ,Map map) 108 | { 109 | try 110 | { 111 | FileInputStream in = new FileInputStream(demoFile); 112 | HWPFDocument hdt = new HWPFDocument(in); 113 | // Fields fields = hdt.getFields(); 114 | // 读取word文本内容 115 | Range range = hdt.getRange(); 116 | // System.out.println(range.text()); 117 | 118 | // 替换文本内容 119 | for(Map.Entry entry : map.entrySet()) 120 | { 121 | range.replaceText(entry.getKey(), entry.getValue()); 122 | } 123 | ByteArrayOutputStream ostream = new ByteArrayOutputStream(); 124 | FileOutputStream out = new FileOutputStream(newFile, true); 125 | hdt.write(ostream); 126 | // 输出字节流 127 | out.write(ostream.toByteArray()); 128 | out.close(); 129 | ostream.close(); 130 | } 131 | catch(IOException e) 132 | { 133 | e.printStackTrace(); 134 | } 135 | catch(Exception e) 136 | { 137 | e.printStackTrace(); 138 | } 139 | } 140 | 141 | } 142 | -------------------------------------------------------------------------------- /MyPoiWordDemo/app/src/main/java/com/test/poiword/WordHtmlActivity.java: -------------------------------------------------------------------------------- 1 | package com.test.poiword; 2 | 3 | import android.os.Bundle; 4 | import android.support.v4.app.FragmentActivity; 5 | import android.webkit.WebSettings; 6 | import android.webkit.WebView; 7 | 8 | import com.test.poiword.utils.FileUtils; 9 | 10 | import org.apache.poi.hwpf.HWPFDocument; 11 | import org.apache.poi.hwpf.converter.PicturesManager; 12 | import org.apache.poi.hwpf.converter.WordToHtmlConverter; 13 | import org.apache.poi.hwpf.usermodel.Picture; 14 | import org.apache.poi.hwpf.usermodel.PictureType; 15 | import org.w3c.dom.Document; 16 | 17 | import java.io.BufferedWriter; 18 | import java.io.ByteArrayOutputStream; 19 | import java.io.File; 20 | import java.io.FileInputStream; 21 | import java.io.FileNotFoundException; 22 | import java.io.FileOutputStream; 23 | import java.io.IOException; 24 | import java.io.OutputStreamWriter; 25 | import java.util.List; 26 | 27 | import javax.xml.parsers.DocumentBuilderFactory; 28 | import javax.xml.transform.OutputKeys; 29 | import javax.xml.transform.Transformer; 30 | import javax.xml.transform.TransformerFactory; 31 | import javax.xml.transform.dom.DOMSource; 32 | import javax.xml.transform.stream.StreamResult; 33 | 34 | /** 35 | * Created by fuweiwei on 2015/11/28. 36 | */ 37 | public class WordHtmlActivity extends FragmentActivity { 38 | //文件存储位置 39 | private String docPath = "/mnt/sdcard/doc/"; 40 | //文件名称 41 | private String docName = "test.doc"; 42 | //html文件存储位置 43 | private String savePath = "/mnt/sdcard/doc/"; 44 | @Override 45 | protected void onCreate(Bundle savedInstanceState) { 46 | super.onCreate(savedInstanceState); 47 | setContentView(R.layout.html); 48 | String name = docName.substring(0, docName.indexOf(".")); 49 | try { 50 | convert2Html(docPath + docName, savePath + name + ".html"); 51 | } catch (Exception e) { 52 | e.printStackTrace(); 53 | } 54 | //WebView加载显示本地html文件 55 | WebView webView = (WebView)this.findViewById(R.id.office); 56 | WebSettings webSettings = webView.getSettings(); 57 | webSettings.setLoadWithOverviewMode(true); 58 | webSettings.setSupportZoom(true); 59 | webSettings.setBuiltInZoomControls(true); 60 | webView.loadUrl("file:/"+savePath+name+".html"); 61 | } 62 | 63 | /** 64 | * word文档转成html格式 65 | * */ 66 | public void convert2Html(String fileName, String outPutFile) { 67 | HWPFDocument wordDocument = null; 68 | try { 69 | wordDocument = new HWPFDocument(new FileInputStream(fileName)); 70 | WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter( 71 | DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()); 72 | //设置图片路径 73 | wordToHtmlConverter.setPicturesManager(new PicturesManager() { 74 | public String savePicture(byte[] content, 75 | PictureType pictureType, String suggestedName, 76 | float widthInches, float heightInches) { 77 | String name = docName.substring(0, docName.indexOf(".")); 78 | return name + "/" + suggestedName; 79 | } 80 | }); 81 | //保存图片 82 | List pics=wordDocument.getPicturesTable().getAllPictures(); 83 | if(pics!=null){ 84 | for(int i=0;i typeClass = _field.getType();// 属性类型 84 | for (int j = 0; j < columnNames.length; j++) { 85 | String columnName = columnNames[j]; 86 | typeClass = getBasicClass(typeClass); 87 | // if typeclass is basic class ,package.if not,no change 88 | boolean isBasicType = isBasicType(typeClass); 89 | 90 | if (isBasicType) { 91 | if (columnName.equalsIgnoreCase(_field.getName())) {// 是基本类型 92 | String _str = c.getString(c.getColumnIndex(columnName)); 93 | if (_str == null) { 94 | break; 95 | } 96 | _str = _str == null ? "" : _str; 97 | // if value is null,make it to "" 98 | // use the constructor to init a attribute instance by 99 | // the value 100 | Constructor cons = typeClass.getConstructor(String.class); 101 | Object attribute = cons.newInstance(_str); 102 | _field.setAccessible(true); 103 | // give the obj the attr 104 | _field.set(obj, attribute); 105 | break; 106 | } 107 | } else { 108 | Object obj2 = setValuesToFields(c, typeClass);// 递归 109 | _field.set(obj, obj2); 110 | break; 111 | } 112 | 113 | } 114 | } 115 | return obj; 116 | } 117 | 118 | /** 119 | * 判断是不是基本类型 120 | * 121 | * @param typeClass 122 | * @return 123 | */ 124 | @SuppressWarnings("rawtypes") 125 | private static boolean isBasicType(Class typeClass) { 126 | if (typeClass.equals(Integer.class) || typeClass.equals(Long.class) || typeClass.equals(Float.class) || typeClass.equals(Double.class) 127 | || typeClass.equals(Boolean.class) || typeClass.equals(Byte.class) || typeClass.equals(Short.class) || typeClass.equals(String.class)) { 128 | 129 | return true; 130 | 131 | } else { 132 | return false; 133 | } 134 | } 135 | 136 | /** 137 | * 获得包装类 138 | * 139 | * @param typeClass 140 | * @return 141 | */ 142 | @SuppressWarnings("all") 143 | public static Class getBasicClass(Class typeClass) { 144 | Class _class = basicMap.get(typeClass); 145 | if (_class == null) 146 | _class = typeClass; 147 | return _class; 148 | } 149 | 150 | @SuppressWarnings("rawtypes") 151 | private static Map basicMap = new HashMap(); 152 | static { 153 | basicMap.put(int.class, Integer.class); 154 | basicMap.put(long.class, Long.class); 155 | basicMap.put(float.class, Float.class); 156 | basicMap.put(double.class, Double.class); 157 | basicMap.put(boolean.class, Boolean.class); 158 | basicMap.put(byte.class, Byte.class); 159 | basicMap.put(short.class, Short.class); 160 | } 161 | 162 | } -------------------------------------------------------------------------------- /MyPoiWordDemo/app/src/main/java/com/test/poiword/utils/FileUtils.java: -------------------------------------------------------------------------------- 1 | package com.test.poiword.utils; 2 | 3 | import android.text.TextUtils; 4 | 5 | import java.io.BufferedReader; 6 | import java.io.File; 7 | import java.io.FileInputStream; 8 | import java.io.FileNotFoundException; 9 | import java.io.FileOutputStream; 10 | import java.io.FileWriter; 11 | import java.io.IOException; 12 | import java.io.InputStream; 13 | import java.io.InputStreamReader; 14 | import java.io.OutputStream; 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | 18 | /** 19 | * File Utils 20 | *
    21 | * Read or write file 22 | *
  • {@link #readFile(String)} read file
  • 23 | *
  • {@link #readFileToList(String)} read file to string list
  • 24 | *
  • {@link #writeFile(String, String, boolean)} write file from String
  • 25 | *
  • {@link #writeFile(String, String)} write file from String
  • 26 | *
  • {@link #writeFile(String, List, boolean)} write file from String List
  • 27 | *
  • {@link #writeFile(String, List)} write file from String List
  • 28 | *
  • {@link #writeFile(String, InputStream)} write file
  • 29 | *
  • {@link #writeFile(String, InputStream, boolean)} write file
  • 30 | *
  • {@link #writeFile(File, InputStream)} write file
  • 31 | *
  • {@link #writeFile(File, InputStream, boolean)} write file
  • 32 | *
33 | *
    34 | * Operate file 35 | *
  • {@link #moveFile(File, File)} or {@link #moveFile(String, String)}
  • 36 | *
  • {@link #copyFile(String, String)}
  • 37 | *
  • {@link #getFileExtension(String)}
  • 38 | *
  • {@link #getFileName(String)}
  • 39 | *
  • {@link #getFileNameWithoutExtension(String)}
  • 40 | *
  • {@link #getFileSize(String)}
  • 41 | *
  • {@link #deleteFile(String)}
  • 42 | *
  • {@link #isFileExist(String)}
  • 43 | *
  • {@link #isFolderExist(String)}
  • 44 | *
  • {@link #makeFolders(String)}
  • 45 | *
  • {@link #makeDirs(String)}
  • 46 | *
47 | * 48 | * @author fuweiwei 2015-9-2 49 | */ 50 | public class FileUtils { 51 | 52 | public final static String FILE_EXTENSION_SEPARATOR = "."; 53 | 54 | private FileUtils() { 55 | throw new AssertionError(); 56 | } 57 | 58 | /** 59 | * read file 60 | * 61 | * @param filePath 62 | * @param charsetName The name of a supported {@link java.nio.charset.Charset charset} 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 |