文章目录

  • android fileutil 文件管理器通用类
    • 程序系统文件目录 获取系统当前文件目录
    • 系统缓存目
    • 内存卡文件目录
    • 内存卡缓存目录
    • 公共下载文件夹
    • 创建文件夹
    • 格式化文件路径
    • 存储卡是否挂载(存在)
  • fileutil用法
    • sd卡取文件
    • 保存文件到sd
    • 取得文件大小
    • 递归取得文件夹大小
    • 转换文件大小
    • 递归求取目录文件个数
    • 在根目录下搜索文件
    • 搜索sdcard文件
    • 查询文件
    • 查找文件并加入到ArrayList 当中去
    • 根据后缀得到文件类型
    • 改变文件大小显示的内容
    • 判断文件MimeType 类型
    • 拷贝文件
    • 创建文件 file
    • 创建文件 path
    • 向Text文件中写入内容
    • 写入文件
    • 获得文件名
    • 读取文件内容,从第startLine行开始,读取lineCount行
    • 创建文件夹
    • 在SD卡上创建目录
    • 判断SD卡上的文件是否存在
    • 将一个InputStream里面的数据写入到SD卡中
    • 读取文件内容 从文件中一行一行的读取文件
    • 将图片保存到本地时进行压缩, 即将图片从Bitmap形式变为File形式时进行压缩,
    • 将图片从本地读到内存时,进行压缩 ,即图片从File形式变为Bitmap形式
    • 指定分辨率和清晰度的图片压缩
  • android AlertDialog
  • 语音识别简介 来自https://www.cnblogs.com/tuyile006/p/8471622.html

android fileutil 文件管理器通用类

参考来自https://www.cnblogs.com/Jason-Jan/p/7908887.html

public class FileUtil {private FileUtil() {}//****系统文件目录**********************************************************************************************

程序系统文件目录 获取系统当前文件目录

    /*** @return 程序系统文件目录 获取系统当前文件目录*/public static String getFileDir(Context context) {return String.valueOf(context.getFilesDir());}/*** @param context    上下文* @param customPath 自定义路径* @return 程序系统文件目录绝对路径*/public static String getFileDir(Context context, String customPath) {String path = context.getFilesDir() + formatPath(customPath);mkdir(path);return path;}

系统缓存目

//****系统缓存目录**********************************************************************************************/*** @return 程序系统缓存目录*/public static String getCacheDir(Context context) {return String.valueOf(context.getCacheDir());}/*** @param context    上下文* @param customPath 自定义路径* @return 程序系统缓存目录*/public static String getCacheDir(Context context, String customPath) {String path = context.getCacheDir() + formatPath(customPath);mkdir(path);return path;}

内存卡文件目录

//****Sdcard文件目录**********************************************************************************************/*** @return 内存卡文件目录*/public static String getExternalFileDir(Context context) {return String.valueOf(context.getExternalFilesDir(""));}/*** @param context    上下文* @param customPath 自定义路径* @return 内存卡文件目录*/public static String getExternalFileDir(Context context, String customPath) {String path = context.getExternalFilesDir("") + formatPath(customPath);mkdir(path);return path;}

内存卡缓存目录

//****Sdcard缓存目录**********************************************************************************************/*** @return 内存卡缓存目录*/public static String getExternalCacheDir(Context context) {return String.valueOf(context.getExternalCacheDir());}/*** @param context    上下文* @param customPath 自定义路径* @return 内存卡缓存目录*/public static String getExternalCacheDir(Context context, String customPath) {String path = context.getExternalCacheDir() + formatPath(customPath);mkdir(path);return path;}

公共下载文件夹

//****公共文件夹**********************************************************************************************/*** @return 公共下载文件夹*/public static String getPublicDownloadDir() {return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();}

创建文件夹

//****相关工具**********************************************************************************************/*** 创建文件夹** @param DirPath 文件夹路径*/public static void mkdir(String DirPath) {File file = new File(DirPath);if (!(file.exists() && file.isDirectory())) {file.mkdirs();}}

格式化文件路径

    /*** 格式化文件路径* 示例:  传入 "sloop" "/sloop" "sloop/" "/sloop/"* 返回 "/sloop"*/private static String formatPath(String path) {if (!path.startsWith("/"))path = "/" + path;while (path.endsWith("/"))path = new String(path.toCharArray(), 0, path.length() - 1);return path;}

存储卡是否挂载(存在)

    /*** @return 存储卡是否挂载(存在)*/public static boolean isMountSdcard() {String status = Environment.getExternalStorageState();return status.equals(Environment.MEDIA_MOUNTED);}}

fileutil用法

sd卡取文件


public class FileUtil {private static final String TAG = "FileUtil";/*** 从sd卡取文件** @param filename* @return*/public String getFileFromSdcard(String filename) {ByteArrayOutputStream outputStream = null;FileInputStream fis = null;try {outputStream = new ByteArrayOutputStream();File file = new File(Environment.getExternalStorageDirectory(), filename);if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {fis = new FileInputStream(file);int len = 0;byte[] data = new byte[1024];while ((len = fis.read(data)) != -1) {outputStream.write(data, 0, len);}}} catch (Exception e) {e.printStackTrace();} finally {try {outputStream.close();fis.close();} catch (IOException e) {}}return new String(outputStream.toByteArray());}

保存文件到sd

  /*** 保存文件到sd** @param filename* @param content* @return*/public static boolean saveContentToSdcard(String filename, String content) {boolean flag = false;FileOutputStream fos = null;try {File file = new File(Environment.getExternalStorageDirectory(), filename);if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {fos = new FileOutputStream(file);fos.write(content.getBytes());flag = true;}} catch (Exception e) {e.printStackTrace();flag = false;} finally {try {fos.close();} catch (IOException e) {}}return flag;}

取得文件大小

  /*** 取得文件大小** @param f* @return* @throws Exception*/@SuppressWarnings("resource")public static long getFileSizes(File f) throws Exception {long size = 0;if (f.exists()) {FileInputStream fis = null;fis = new FileInputStream(f);size = fis.available();} else {f.createNewFile();}return size;}

递归取得文件夹大小

  /*** 递归取得文件夹大小** @param dir* @return* @throws Exception*/public static long getFileSize(File dir) throws Exception {long size = 0;File flist[] = dir.listFiles();for (int i = 0; i < flist.length; i++) {if (flist[i].isDirectory()) {size = size + getFileSize(flist[i]);} else {size = size + flist[i].length();}}return size;}

转换文件大小

  /*** 转换文件大小** @param fileS* @return*/public static String FormetFileSize(long fileS) {DecimalFormat df = new DecimalFormat("#.00");String fileSizeString = "";if (fileS < 1024) {fileSizeString = df.format((double) fileS) + "B";} else if (fileS < 1048576) {fileSizeString = df.format((double) fileS / 1024) + "K";} else if (fileS < 1073741824) {fileSizeString = df.format((double) fileS / 1048576) + "M";} else {fileSizeString = df.format((double) fileS / 1073741824) + "G";}return fileSizeString;}

递归求取目录文件个数

  /*** 递归求取目录文件个数** @param f* @return*/public static long getlist(File f) {long size = 0;File flist[] = f.listFiles();size = flist.length;for (int i = 0; i < flist.length; i++) {if (flist[i].isDirectory()) {size = size + getlist(flist[i]);size--;}}return size;}

在根目录下搜索文件

  /*** 在根目录下搜索文件** @param keyword* @return*/public static String searchFile(String keyword) {String result = "";File[] files = new File("/").listFiles();for (File file : files) {if (file.getName().indexOf(keyword) >= 0) {result += file.getPath() + "\n";}}if (result.equals("")) {result = "找不到文件!!";}return result;}

搜索sdcard文件

  /*** @detail 搜索sdcard文件* @param 需要进行文件搜索的目录* @param 过滤搜索文件类型* */public static List<String> search(File file, String[] ext) {List<String> list = new ArrayList<String>();if (file != null) {if (file.isDirectory()) {File[] listFile = file.listFiles();if (listFile != null) {for (int i = 0; i < listFile.length; i++) {search(listFile[i], ext);}}} else {String filename = file.getAbsolutePath();for (int i = 0; i < ext.length; i++) {if (filename.endsWith(ext[i])) {list.add(filename);break;}}}}return list;}

查询文件

  /*** 查询文件** @param file* @param keyword* @return*/public static List<File> FindFile(File file, String keyword) {List<File> list = new ArrayList<File>();if (file.isDirectory()) {File[] files = file.listFiles();if (files != null) {for (File tempf : files) {if (tempf.isDirectory()) {if (tempf.getName().toLowerCase().lastIndexOf(keyword) > -1) {list.add(tempf);}list.addAll(FindFile(tempf, keyword));} else {if (tempf.getName().toLowerCase().lastIndexOf(keyword) > -1) {list.add(tempf);}}}}}return list;}

查找文件并加入到ArrayList 当中去

  /*** searchFile 查找文件并加入到ArrayList 当中去** @param context* @param keyword* @param filepath* @return*/public static List<Map<String, Object>> searchFile(Context context, String keyword, File filepath) {List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();Map<String, Object> rowItem = null;int index = 0;// 判断SD卡是否存在if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {File[] files = filepath.listFiles();if (files.length > 0) {for (File file : files) {if (file.isDirectory()) {if (file.getName().toLowerCase().lastIndexOf(keyword) > -1) {rowItem = new HashMap<String, Object>();rowItem.put("number", index); // 加入序列号rowItem.put("fileName", file.getName());// 加入名称rowItem.put("path", file.getPath()); // 加入路径rowItem.put("size", file.length() + ""); // 加入文件大小list.add(rowItem);}// 如果目录可读就执行(一定要加,不然会挂掉)if (file.canRead()) {list.addAll(searchFile(context, keyword, file)); // 如果是目录,递归查找}} else {// 判断是文件,则进行文件名判断try {if (file.getName().indexOf(keyword) > -1 || file.getName().indexOf(keyword.toUpperCase()) > -1) {rowItem = new HashMap<String, Object>();rowItem.put("number", index); // 加入序列号rowItem.put("fileName", file.getName());// 加入名称rowItem.put("path", file.getPath()); // 加入路径rowItem.put("size", file.length() + ""); // 加入文件大小list.add(rowItem);index++;}} catch (Exception e) {Toast.makeText(context, "查找发生错误!", Toast.LENGTH_SHORT).show();}}}}}return list;}

根据后缀得到文件类型

  /*** 根据后缀得到文件类型** @param fileName* @param pointIndex* @return*/public static String getFileType(String fileName, int pointIndex) {String type = fileName.substring(pointIndex + 1).toLowerCase();if ("m4a".equalsIgnoreCase(type) || "xmf".equalsIgnoreCase(type) || "ogg".equalsIgnoreCase(type) || "wav".equalsIgnoreCase(type)|| "m4a".equalsIgnoreCase(type) || "aiff".equalsIgnoreCase(type) || "midi".equalsIgnoreCase(type)|| "vqf".equalsIgnoreCase(type) || "aac".equalsIgnoreCase(type) || "flac".equalsIgnoreCase(type)|| "tak".equalsIgnoreCase(type) || "wv".equalsIgnoreCase(type)) {type = "ic_file_audio";} else if ("mp3".equalsIgnoreCase(type) || "mid".equalsIgnoreCase(type)) {type = "ic_file_mp3";} else if ("avi".equalsIgnoreCase(type) || "mp4".equalsIgnoreCase(type) || "dvd".equalsIgnoreCase(type)|| "mid".equalsIgnoreCase(type) || "mov".equalsIgnoreCase(type) || "mkv".equalsIgnoreCase(type)|| "mp2v".equalsIgnoreCase(type) || "mpe".equalsIgnoreCase(type) || "mpeg".equalsIgnoreCase(type)|| "mpg".equalsIgnoreCase(type) || "asx".equalsIgnoreCase(type) || "asf".equalsIgnoreCase(type)|| "flv".equalsIgnoreCase(type) || "navi".equalsIgnoreCase(type) || "divx".equalsIgnoreCase(type)|| "rm".equalsIgnoreCase(type) || "rmvb".equalsIgnoreCase(type) || "dat".equalsIgnoreCase(type)|| "mpa".equalsIgnoreCase(type) || "vob".equalsIgnoreCase(type) || "3gp".equalsIgnoreCase(type)|| "swf".equalsIgnoreCase(type) || "wmv".equalsIgnoreCase(type)) {type = "ic_file_video";} else if ("bmp".equalsIgnoreCase(type) || "pcx".equalsIgnoreCase(type) || "tiff".equalsIgnoreCase(type)|| "gif".equalsIgnoreCase(type) || "jpeg".equalsIgnoreCase(type) || "tga".equalsIgnoreCase(type)|| "exif".equalsIgnoreCase(type) || "fpx".equalsIgnoreCase(type) || "psd".equalsIgnoreCase(type)|| "cdr".equalsIgnoreCase(type) || "raw".equalsIgnoreCase(type) || "eps".equalsIgnoreCase(type)|| "gif".equalsIgnoreCase(type) || "jpg".equalsIgnoreCase(type) || "jpeg".equalsIgnoreCase(type)|| "png".equalsIgnoreCase(type) || "hdri".equalsIgnoreCase(type) || "ai".equalsIgnoreCase(type)) {type = "ic_file_image";} else if ("ppt".equalsIgnoreCase(type) || "doc".equalsIgnoreCase(type) || "xls".equalsIgnoreCase(type)|| "pps".equalsIgnoreCase(type) || "xlsx".equalsIgnoreCase(type) || "xlsm".equalsIgnoreCase(type)|| "pptx".equalsIgnoreCase(type) || "pptm".equalsIgnoreCase(type) || "ppsx".equalsIgnoreCase(type)|| "maw".equalsIgnoreCase(type) || "mdb".equalsIgnoreCase(type) || "pot".equalsIgnoreCase(type)|| "msg".equalsIgnoreCase(type) || "oft".equalsIgnoreCase(type) || "xlw".equalsIgnoreCase(type)|| "wps".equalsIgnoreCase(type) || "rtf".equalsIgnoreCase(type) || "ppsm".equalsIgnoreCase(type)|| "potx".equalsIgnoreCase(type) || "potm".equalsIgnoreCase(type) || "ppam".equalsIgnoreCase(type)) {type = "ic_file_office";} else if ("txt".equalsIgnoreCase(type) || "text".equalsIgnoreCase(type) || "chm".equalsIgnoreCase(type)|| "hlp".equalsIgnoreCase(type) || "pdf".equalsIgnoreCase(type) || "doc".equalsIgnoreCase(type)|| "docx".equalsIgnoreCase(type) || "docm".equalsIgnoreCase(type) || "dotx".equalsIgnoreCase(type)) {type = "ic_file_text";} else if ("ini".equalsIgnoreCase(type) || "sys".equalsIgnoreCase(type) || "dll".equalsIgnoreCase(type)|| "adt".equalsIgnoreCase(type)) {type = "ic_file_system";} else if ("rar".equalsIgnoreCase(type) || "zip".equalsIgnoreCase(type) || "arj".equalsIgnoreCase(type)|| "gz".equalsIgnoreCase(type) || "z".equalsIgnoreCase(type) || "7Z".equalsIgnoreCase(type) || "GZ".equalsIgnoreCase(type)|| "BZ".equalsIgnoreCase(type) || "ZPAQ".equalsIgnoreCase(type)) {type = "ic_file_rar";} else if ("html".equalsIgnoreCase(type) || "htm".equalsIgnoreCase(type) || "java".equalsIgnoreCase(type)|| "php".equalsIgnoreCase(type) || "asp".equalsIgnoreCase(type) || "aspx".equalsIgnoreCase(type)|| "jsp".equalsIgnoreCase(type) || "shtml".equalsIgnoreCase(type) || "xml".equalsIgnoreCase(type)) {type = "ic_file_web";} else if ("exe".equalsIgnoreCase(type) || "com".equalsIgnoreCase(type) || "bat".equalsIgnoreCase(type)|| "iso".equalsIgnoreCase(type) || "msi".equalsIgnoreCase(type)) {type = "ic_file_exe";} else if ("apk".equalsIgnoreCase(type)) {type = "ic_file_apk";} else {type = "ic_file_normal";}return type;}

改变文件大小显示的内容

  /*** 改变文件大小显示的内容** @param size* @return*/public static String changeFileSize(String size) {if (Integer.parseInt(size) > 1024) {size = Integer.parseInt(size) / 1024 + "K";} else if (Integer.parseInt(size) > (1024 * 1024)) {size = Integer.parseInt(size) / (1024 * 1024) + "M";} else if (Integer.parseInt(size) > (1024 * 1024 * 1024)) {size = Integer.parseInt(size) / (1024 * 1024 * 1024) + "G";} else {size += "B";}return size;}/*** 得到所有文件** @param dir* @return*/public static ArrayList<File> getAllFiles(File dir) {ArrayList<File> allFiles = new ArrayList<File>();// 递归取得目录下的所有文件及文件夹File[] files = dir.listFiles();for (int i = 0; i < files.length; i++) {File file = files[i];allFiles.add(file);if (file.isDirectory()) {getAllFiles(file);}}Logger.i("test", allFiles.size() + "");return allFiles;}

判断文件MimeType 类型

  /*** 判断文件MimeType 类型** @param f* @return*/public static String getMIMEType(File f) {String type = "";String fName = f.getName();/* 取得扩展名 */String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();/* 依扩展名的类型决定MimeType */if (end.equalsIgnoreCase("m4a") || end.equalsIgnoreCase("mp3") || end.equalsIgnoreCase("mid") || end.equalsIgnoreCase("xmf")|| end.equalsIgnoreCase("ogg") || end.equalsIgnoreCase("wav")) {type = "audio";} else if (end.equalsIgnoreCase("3gp") || end.equalsIgnoreCase("mp4")) {type = "video";} else if (end.equalsIgnoreCase("jpg") || end.equalsIgnoreCase("gif") || end.equalsIgnoreCase("png")|| end.equalsIgnoreCase("jpeg") || end.equalsIgnoreCase("bmp")) {type = "image";} else if (end.equalsIgnoreCase("apk")) {/* android.permission.INSTALL_PACKAGES */type = "application/vnd.android.package-archive";} else if (end.equalsIgnoreCase("txt") || end.equalsIgnoreCase("java")) {/* android.permission.INSTALL_PACKAGES */type = "text";} else {type = "*";}/* 如果无法直接打开,就跳出软件列表给用户选择 */if (end.equalsIgnoreCase("apk")) {} else {type += "/*";}return type;}

拷贝文件

  /*** 拷贝文件** @param fromFile* @param toFile* @throws IOException*/public static void copyFile(File fromFile, String toFile) throws IOException {FileInputStream from = null;FileOutputStream to = null;try {from = new FileInputStream(fromFile);to = new FileOutputStream(toFile);byte[] buffer = new byte[1024];int bytesRead;while ((bytesRead = from.read(buffer)) != -1)to.write(buffer, 0, bytesRead); // write} finally {if (from != null)try {from.close();} catch (IOException e) {Log.e(TAG, "", e);}if (to != null)try {to.close();} catch (IOException e) {Log.e(TAG, "", e);}}}

创建文件 file

  /*** 创建文件** @param file* @return*/public static File createNewFile(File file) {try {if (file.exists()) {return file;}File dir = file.getParentFile();if (!dir.exists()) {dir.mkdirs();}if (!file.exists()) {file.createNewFile();}} catch (IOException e) {Log.e(TAG, "", e);return null;}return file;}

创建文件 path

  /*** 创建文件** @param path*/public static File createNewFile(String path) {File file = new File(path);return createNewFile(file);}// end method createText()/*** 删除文件** @param path*/public static void deleteFile(String path) {File file = new File(path);deleteFile(file);}/*** 删除文件** @param file*/public static void deleteFile(File file) {if (!file.exists()) {return;}if (file.isFile()) {file.delete();} else if (file.isDirectory()) {File files[] = file.listFiles();for (int i = 0; i < files.length; i++) {deleteFile(files[i]);}}file.delete();}

向Text文件中写入内容

  /*** 向Text文件中写入内容** @param file* @param content* @return*/public static boolean write(String path, String content) {return write(path, content, false);}public static boolean write(String path, String content, boolean append) {return write(new File(path), content, append);}public static boolean write(File file, String content) {return write(file, content, false);}

写入文件

  /*** 写入文件** @param file* @param content* @param append* @return*/public static boolean write(File file, String content, boolean append) {if (file == null || StringUtil.empty(content)) {return false;}if (!file.exists()) {file = createNewFile(file);}FileOutputStream fos = null;try {fos = new FileOutputStream(file, append);fos.write(content.getBytes());} catch (Exception e) {Log.e(TAG, "", e);return false;} finally {try {fos.close();} catch (IOException e) {Log.e(TAG, "", e);}fos = null;}return true;}

获得文件名

  /*** 获得文件名** @param path* @return*/public static String getFileName(String path) {if (StringUtil.empty(path)) {return null;}File f = new File(path);String name = f.getName();f = null;return name;}

读取文件内容,从第startLine行开始,读取lineCount行

  /*** 读取文件内容,从第startLine行开始,读取lineCount行** @param file* @param startLine* @param lineCount* @return 读到文字的list,如果list.size<lineCount则说明读到文件末尾了*/public static List<String> readFile(File file, int startLine, int lineCount) {if (file == null || startLine < 1 || lineCount < 1) {return null;}if (!file.exists()) {return null;}FileReader fileReader = null;List<String> list = null;try {list = new ArrayList<String>();fileReader = new FileReader(file);LineNumberReader lineReader = new LineNumberReader(fileReader);boolean end = false;for (int i = 1; i < startLine; i++) {if (lineReader.readLine() == null) {end = true;break;}}if (end == false) {for (int i = startLine; i < startLine + lineCount; i++) {String line = lineReader.readLine();if (line == null) {break;}list.add(line);}}} catch (Exception e) {Log.e(TAG, "read log error!", e);} finally {if (fileReader != null) {try {fileReader.close();} catch (IOException e) {e.printStackTrace();}}}return list;}

创建文件夹

  /*** 创建文件夹** @param dir* @return*/public static boolean createDir(File dir) {try {if (!dir.exists()) {dir.mkdirs();}return true;} catch (Exception e) {Log.e(TAG, "create dir error", e);return false;}}

在SD卡上创建目录

  /*** 在SD卡上创建目录** @param dirName*/public static File creatSDDir(String dirName) {File dir = new File(dirName);dir.mkdir();return dir;}

判断SD卡上的文件是否存在

  /*** 判断SD卡上的文件是否存在*/public static boolean isFileExist(String fileName) {File file = new File(fileName);return file.exists();}

将一个InputStream里面的数据写入到SD卡中

  /*** 将一个InputStream里面的数据写入到SD卡中*/public static File write2SDFromInput(String path, String fileName, InputStream input) {File file = null;OutputStream output = null;try {creatSDDir(path);file = createNewFile(path + "/" + fileName);output = new FileOutputStream(file);byte buffer[] = new byte[1024];int len = -1;while ((len = input.read(buffer)) != -1) {output.write(buffer, 0, len);}output.flush();} catch (Exception e) {e.printStackTrace();} finally {try {output.close();} catch (Exception e) {e.printStackTrace();}}return file;}

读取文件内容 从文件中一行一行的读取文件

  /*** 读取文件内容 从文件中一行一行的读取文件** @param file* @return*/public static String readFile(File file) {Reader read = null;String content = "";String result = "";BufferedReader br = null;try {read = new FileReader(file);br = new BufferedReader(read);while ((content = br.readLine().toString().trim()) != null) {result += content + "\r\n";}} catch (Exception e) {e.printStackTrace();} finally {try {read.close();br.close();} catch (Exception e) {e.printStackTrace();}}return result;}

将图片保存到本地时进行压缩, 即将图片从Bitmap形式变为File形式时进行压缩,

  /*** 将图片保存到本地时进行压缩, 即将图片从Bitmap形式变为File形式时进行压缩,* 特点是: File形式的图片确实被压缩了, 但是当你重新读取压缩后的file为 Bitmap是,它占用的内存并没有改变** @param bmp* @param file*/public static void compressBmpToFile(Bitmap bmp, File file) {ByteArrayOutputStream baos = new ByteArrayOutputStream();int options = 80;// 个人喜欢从80开始,bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);while (baos.toByteArray().length / 1024 > 100) {baos.reset();options -= 10;bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);}try {FileOutputStream fos = new FileOutputStream(file);fos.write(baos.toByteArray());fos.flush();fos.close();} catch (Exception e) {e.printStackTrace();}}

将图片从本地读到内存时,进行压缩 ,即图片从File形式变为Bitmap形式

  /*** 将图片从本地读到内存时,进行压缩 ,即图片从File形式变为Bitmap形式* 特点: 通过设置采样率, 减少图片的像素, 达到对内存中的Bitmap进行压缩* @param srcPath* @return*/public static Bitmap compressImageFromFile(String srcPath, float pixWidth, float pixHeight) {BitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true;// 只读边,不读内容Bitmap bitmap = BitmapFactory.decodeFile(srcPath, options);options.inJustDecodeBounds = false;int w = options.outWidth;int h = options.outHeight;//float pixWidth = 800f;////float pixHeight = 480f;//int scale = 1;if (w > h && w > pixWidth) {scale = (int) (options.outWidth / pixWidth);} else if (w < h && h > pixHeight) {scale = (int) (options.outHeight / pixHeight);}if (scale <= 0)scale = 1;options.inSampleSize = scale;// 设置采样率options.inPreferredConfig = Config.ARGB_8888;// 该模式是默认的,可不设options.inPurgeable = true;// 同时设置才会有效options.inInputShareable = true;// 。当系统内存不够时候图片自动被回收bitmap = BitmapFactory.decodeFile(srcPath, options);// return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩// 其实是无效的,大家尽管尝试return bitmap;}

指定分辨率和清晰度的图片压缩

  /***  指定分辨率和清晰度的图片压缩*/public void transImage(String fromFile, String toFile, int width, int height, int quality){try{Bitmap bitmap = BitmapFactory.decodeFile(fromFile);int bitmapWidth = bitmap.getWidth();int bitmapHeight = bitmap.getHeight();// 缩放图片的尺寸float scaleWidth = (float) width / bitmapWidth;float scaleHeight = (float) height / bitmapHeight;Matrix matrix = new Matrix();matrix.postScale(scaleWidth, scaleHeight);// 产生缩放后的Bitmap对象Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false);// save fileFile myCaptureFile = new File(toFile);FileOutputStream out = new FileOutputStream(myCaptureFile);if(resizeBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)){out.flush();out.close();}if(!bitmap.isRecycled()){bitmap.recycle();//记得释放资源,否则会内存溢出}if(!resizeBitmap.isRecycled()){resizeBitmap.recycle();}}catch (FileNotFoundException e){e.printStackTrace();}catch (IOException ex){ex.printStackTrace();}}
}

android AlertDialog

弹出对话框链接:https://www.jianshu.com/p/cef3fb27c4e7

AlertDialog dialog = new AlertDialog.Builder(this).create();//创建对话框
dialog.setIcon(R.mipmap.ic_launcher);//设置对话框icondialog.setTitle("这是一个AlertDialog");//设置对话框标题
dialog.setMessage("Hello world");//设置文字显示内容
//分别设置三个buttondialog.setButton(DialogInterface.BUTTON_POSITIVE,"确定", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {dialog.dismiss();//关闭对话框 }});
dialog.setButton(DialogInterface.BUTTON_NEUTRAL,"点我试试", new DialogInterface.OnClickListener() {@Override public void onClick(DialogInterface dialog, int which) { }});dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();//关闭对话框 }});dialog.show();//显示对话框

AlertDialog的三个button对应DialogInterface中的三个常量,分别是:BUTTON_NEUTRAL,BUTTON_POSITIVE,BUTTON_NEGATIVE。不同的常量所对应的button位置不同。
AlertDialog dialog = new AlertDialog.Builder(this).create();的Builder()中传入的context参数必须来自activity,而不能是application的,否则会报错。
•调用dismiss()方法可以关闭对话框。除了在button点击事件中,还可以用在CheckBox、RadioButton的onCheckedChanged事件中等,以实现在用户完成选择以后自动关闭对话框的功能。

.builder

//初始化字符串数组
final String[] strArray = new String[]{"床前明月光","意识地上霜","举头望明月","低头思故乡"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);//实例化
builderbuilder.setIcon(R.mipmap.ic_launcher);//设置图标
builder.setTitle("简单列表");//设置标题
//设置列表
builder.setItems(strArray, new DialogInterface.OnClickListener() {
@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(MainActivity.this,strArray[which],Toast.LENGTH_SHORT).show();}});builder.create().show();//创建并显示对话框
///
//
//
////设置单选列表builder.setSingleChoiceItems(strArray, 0, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {}});//设置多选列表
/* builder.setMultiChoiceItems(strArray, new boolean[]{false, false, false, false}, new DialogInterface.OnMultiChoiceClickListener() {@Override public void onClick(DialogInterface dialog, int which, boolean isChecked) {}});*///创建对话框AlertDialog dialog = builder.create(); //设置确定按钮 dialog.setButton(DialogInterface.BUTTON_POSITIVE,"确定", new DialogInterface.OnClickListener() { @Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();}});dialog.show();//显示对话框

通过引入布局文件来自定义对话框布局

//实例化布局View view = LayoutInflater.from(this).inflate(R.layout.item_custom,null); //找到并对自定义布局中的控件进行操作的示例 EditText account = (EditText)view.findViewById(R.id.account);account.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}@Override public void onTextChanged(CharSequence s, int start, int before, int count){} @Override public void afterTextChanged(Editable s){}}); //创建对话框AlertDialog dialog = new AlertDialog.Builder(this).create();dialog.setIcon(R.mipmap.ic_launcher);//设置图标 dialog.setTitle("自定义布局对话框");//设置标题dialog.setView(view);//添加布局 //设置按键 dialog.setButton(AlertDialog.BUTTON_POSITIVE, "登陆", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {}});dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {@Override public void onClick(DialogInterface dialog, int which) {}});dialog.show();

Dialog自定义位置大小动画

Window dialogWindow = dialog.getWindow();//获取window对象
dialogWindow.setGravity(Gravity.BOTTOM);//设置对话框位置
dialogWindow.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);//设置横向全屏
dialogWindow.setWindowAnimations(R.style.share_animation);//设置动画
WindowManager m = getWindowManager();
Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值p.height = (int) (d.getHeight() * 0.6); // 高度设置为屏幕的0.6 p.width = (int) (d.getWidth() * 0.65); // 宽度设置为屏幕的0.65 dialogWindow.setAttributes(p);
//stytle.xml中
<style name="share_animation" parent="android:Animation">
<item name="@android:windowEnterAnimation">@anim/dialog_enter</item> //进入时的动画<item name="@android:windowExitAnimation">@anim/dialog_exit</item> //退出时的动画 </style> Window dialogWindow = dialog.getWindow();
WindowManager.LayoutParams lp = dialogWindow.getAttributes();
dialogWindow.setGravity(Gravity.LEFT | Gravity.TOP); /** lp.x与lp.y表示相对于原始位置的偏移.
* 当参数值包含Gravity.LEFT时,对话框出现在左边,所以lp.x就表示相对左边的偏移,负值忽略.
* * 当参数值包含Gravity.RIGHT时,对话框出现在右边,所以lp.x就表示相对右边的偏移,负值忽略.*
*  当参数值包含Gravity.TOP时,对话框出现在上边,所以lp.y就表示相对上边的偏移,负值忽略.*
* 当参数值包含Gravity.BOTTOM时,对话框出现在下边,所以lp.y就表示相对下边的偏移,负值忽略.*
*  当参数值包含Gravity.CENTER_HORIZONTAL时 * ,对话框水平居中,所以lp.x就表示在水平居中的位置移动lp.x像素,正值向右移动,负值向左移动.*
*  当参数值包含Gravity.CENTER_VERTICAL时 * ,对话框垂直居中,所以lp.y就表示在垂直居中的位置移动lp.y像素,正值向右移动,负值向左移动.*
* gravity的默认值为Gravity.CENTER,即Gravity.CENTER_HORIZONTAL |*
* Gravity.CENTER_VERTICAL.** 本来setGravity的参数值为Gravity.LEFT | Gravity.TOP时对话框应出现在程序的左上角,但在 手机上测试时发现距左边与上边都有一小段距离,而且垂直坐标把程序标题栏也计算在内了,*
*  Gravity.LEFT, Gravity.TOP, Gravity.BOTTOM与Gravity.RIGHT都是如此,据边界有一小段距离 *
* / lp.x = 100; // 新位置X坐标 lp.y = 100;
* // 新位置Y坐标 lp.width = 300; //
* 宽度 lp.height = 300; //
*  高度 lp.alpha = 0.7f; //
*  透明度 // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes // dialog.onWindowAttributesChanged(lp);dialogWindow.setAttributes(lp); 

语音识别简介 来自https://www.cnblogs.com/tuyile006/p/8471622.html

简要给大家介绍一下语音怎么变文字的吧。希望这个介绍能让所有同学看懂。

首先,我们知道声音实际上是一种波。常见的mp3、wmv等格式都是压缩格式,必须转成非压缩的纯波形文件来处理,比如Windows PCM文件,也就是俗称的wav文件。wav文件里存储的除了一个文件头以外,就是声音波形的一个个点了。下图是一个波形的示例。

在开始语音识别之前,有时需要把首尾端的静音切除,降低对后续步骤造成的干扰。这个静音切除的操作一般称为VAD,需要用到信号处理的一些技术。要对声音进行分析,需要对声音分帧,也就是把声音切开成一小段一小段,每小段称为一帧。分帧操作一般不是简单的切开,而是使用移动窗函数来实现,这里不详述。帧与帧之间一般是有交叠的,就像下图这样:

图中,每帧的长度为25毫秒,每两帧之间有25-10=15毫秒的交叠。我们称为以帧长25ms、帧移10ms分帧。图中,每帧的长度为25毫秒,每两帧之间有25-10=15毫秒的交叠。我们称为以帧长25ms、帧移10ms分帧。

分帧后,语音就变成了很多小段。但波形在时域上几乎没有描述能力,因此必须将波形作变换。常见的一种变换方法是提取MFCC特征,根据人耳的生理特性,把每一帧波形变成一个多维向量,可以简单地理解为这个向量包含了这帧语音的内容信息。这个过程叫做声学特征提取。实际应用中,这一步有很多细节,声学特征也不止有MFCC这一种,具体这里不讲。

至此,声音就成了一个12行(假设声学特征是12维)、N列的一个矩阵,称之为观察序列,这里N为总帧数。观察序列如下图所示,图中,每一帧都用一个12维的向量表示,色块的颜色深浅表示向量值的大小。

接下来就要介绍怎样把这个矩阵变成文本了。首先要介绍两个概念:

1.音素:单词的发音由音素构成。对英语,一种常用的音素集是卡内基梅隆大学的一套由39个音素构成的音素集,参见The CMU Pronouncing Dictionary。汉语一般直接用全部声母和韵母作为音素集,另外汉语识别还分有调无调,不详述。

2.状态:这里理解成比音素更细致的语音单位就行啦。通常把一个音素划分成3个状态。

语音识别是怎么工作的呢?实际上一点都不神秘,无非是:

第一步,把帧识别成状态(难点);

第二步,把状态组合成音素;

第三步,把音素组合成单词。

如下图所示:

图中,每个小竖条代表一帧,若干帧语音对应一个状态,每三个状态组合成一个音素,若干个音素组合成一个单词。也就是说,只要知道每帧语音对应哪个状态了,语音识别的结果也就出来了。图中,每个小竖条代表一帧,若干帧语音对应一个状态,每三个状态组合成一个音素,若干个音素组合成一个单词。也就是说,只要知道每帧语音对应哪个状态了,语音识别的结果也就出来了。

那每帧音素对应哪个状态呢?有个容易想到的办法,看某帧对应哪个状态的概率最大,那这帧就属于哪个状态。比如下面的示意图,这帧对应S3状态的概率最大,因此就让这帧属于S3状态。

那这些用到的概率从哪里读取呢?有个叫“声学模型”的东西,里面存了一大堆参数,通过这些参数,就可以知道帧和状态对应的概率。获取这一大堆参数的方法叫做“训练”,需要使用巨大数量的语音数据,训练的方法比较繁琐,这里不讲。

但这样做有一个问题:每一帧都会得到一个状态号,最后整个语音就会得到一堆乱七八糟的状态号,相邻两帧间的状态号基本都不相同。假设语音有1000帧,每帧对应1个状态,每3个状态组合成一个音素,那么大概会组合成300个音素,但这段语音其实根本没有这么多音素。如果真这么做,得到的状态号可能根本无法组合成音素。实际上,相邻帧的状态应该大多数都是相同的才合理,因为每帧很短。

解决这个问题的常用方法就是使用隐马尔可夫模型(Hidden Markov Model,HMM)。这东西听起来好像很高深的样子,实际上用起来很简单:

第一步,构建一个状态网络。

第二步,从状态网络中寻找与声音最匹配的路径。

这样就把结果限制在预先设定的网络中,避免了刚才说到的问题,当然也带来一个局限,比如你设定的网络里只包含了“今天晴天”和“今天下雨”两个句子的状态路径,那么不管说些什么,识别出的结果必然是这两个句子中的一句。

那如果想识别任意文本呢?把这个网络搭得足够大,包含任意文本的路径就可以了。但这个网络越大,想要达到比较好的识别准确率就越难。所以要根据实际任务的需求,合理选择网络大小和结构。

搭建状态网络,是由单词级网络展开成音素网络,再展开成状态网络。语音识别过程其实就是在状态网络中搜索一条最佳路径,语音对应这条路径的概率最大,这称之为“解码”。路径搜索的算法是一种动态规划剪枝的算法,称之为Viterbi算法,用于寻找全局最优路径。

这里所说的累积概率,由三部分构成,分别是:

1.观察概率:每帧和每个状态对应的概率

2.转移概率:每个状态转移到自身或转移到下个状态的概率

3.语言概率:根据语言统计规律得到的概率

其中,前两种概率从声学模型中获取,最后一种概率从语言模型中获取。语言模型是使用大量的文本训练出来的,可以利用某门语言本身的统计规律来帮助提升识别正确率。语言模型很重要,如果不使用语言模型,当状态网络较大时,识别出的结果基本是一团乱麻。

以上介绍的是传统的基于HMM的语音识别。事实上,HMM的内涵绝不是上面所说的“无非是个状态网络”那么简单。以上的文字只是想让大家容易理解,并不追求严谨。

android fileutil alertDialog相关推荐

  1. Android的AlertDialog详解

    AlertDialog的构造方法全部是Protected的,所以不能直接通过new一个AlertDialog来创建出一个AlertDialog. 要创建一个AlertDialog,就要用到AlertD ...

  2. Android 自定义AlertDialog,调用方法与系统一致

    2019独角兽企业重金招聘Python工程师标准>>> 由于android原生的AlertDialog都一致,有时为了和你的项目的Dialog保持一致,你最先想到的就是有没有Aler ...

  3. Android 自定义AlertDialog对话框

    2019独角兽企业重金招聘Python工程师标准>>> 系统默认的AlertDialog,与项目的UI不统一,所以,改了一下,定义了一样式,最终效果如下图: 另外,为了尽量少改原来的 ...

  4. Android 自定义AlertDialog类

    还是先从最简单的开始吧,然后一步一步的扩展. 为了保证软件上所谓的低耦合度和可重用性,这里不得不需要单独建立一个类CustomerDialog,然后继承AlertDialog public class ...

  5. Android自定义AlertDialog的控件获取操作

    Android自定义AlertDialog的控件获取操作 在自定义的AlertDialog布局虽然可以显示,但是试过很多方法都不能获得其中的控件进行操作,找了很多方法最后这种方法可以. dialog的 ...

  6. Android的AlertDialog详解(7种方式)

    需要注意的两点: 1. 在setIcon时,需要使用setTitle方法,否则icon不会显示 2.如果同时调用setMessage 和 setItems(或者setSingleChoiceItems ...

  7. Android中Alertdialog对话框点击消失?

    在开发的时候遇到一个问题,就是一触摸对话框边缘外部,对话框会自动消失.这个问题很纠结啊,查找了一下发现从Android 4.0开始,AlertDialog有了变化,就是在触摸对话框边缘外部,对话框会自 ...

  8. android service alertdialog,Android service里面启动alertdialog

    public void showSystemDialog(String showInfo, final int flag) 2 { 3 AlertDialog.Builder b = new Aler ...

  9. Android FileUtil(android文件工具类)

    android开发和Java开发差不了多少,也会有许多相同的功能.像本文提到的文件存储,在Java项目和android项目里面用到都是相同的.只是android开发的一些路径做了相应的处理. 下面就是 ...

最新文章

  1. 机器人控制与感知有感
  2. net-speeder 安装
  3. Vb 与 Vc 的区别
  4. MySQL服务的启动和停止
  5. 如何在S/4HANA里创建Custom Business object并实现自定义逻辑
  6. where is Fiori count server execution interval configured
  7. c语言中 文件的字符串输入函数是6,【C语言】文件操作及输入输出格式(文件常用的库函数)...
  8. oracle的SCN和Checkpoint_Change#的关系
  9. 哪些手机支持双wifi?
  10. 紧急事态分析及处理方法
  11. Python代码混淆工具,Python源代码保密、加密、混淆
  12. 塞班系统微信连接不上服务器,充满情怀的塞班系统:手机QQ、微信将无法登陆使用...
  13. ios wifi 定位_Wifi 定位原理及 iOS Wifi 列表获取(示例代码)
  14. word文档无法另存为/导出pdf解决办法
  15. 迷宫小游戏c语言代码,C语言编写的迷宫小游戏-源代码
  16. 给诸位想换工作的IT同学的一些建议
  17. “机器学习实战”刻意练习——分类问题:决策树
  18. 虚拟主机怎么用?香港虚拟主机搭建网站教程
  19. android获取后一天日期,android获取本周本月本年的第一天和最后一天
  20. win10系统如何把U盘刷成FAT格式?

热门文章

  1. 【动态规划】货币面值
  2. 如何用MOS管来实现电源防反接电路
  3. FPN论文解读 和 代码详解
  4. 物流管理和计算机那个专业好,我是学计算机的女生,想跨专业考物流管理专业的研究生,好不好?...
  5. navicat for Oracle 连接远程oracle配置
  6. 基于kendryte K210 的Sipeed M1W上电
  7. 国密版 Nginx服务器安装
  8. antd中前段处理字符串转为Int
  9. 神经网络梯度反向传播公式
  10. java 前言中不允许有内容,Java解析XML文档给出了“序言中不允许的内容”。