FileUtil.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. package com.sunzee.utils;
  2. import android.graphics.Bitmap;
  3. import android.graphics.BitmapFactory;
  4. import android.text.TextUtils;
  5. import android.util.Log;
  6. import com.sunzee.model.domain.Name;
  7. import java.io.BufferedReader;
  8. import java.io.File;
  9. import java.io.FileInputStream;
  10. import java.io.FileNotFoundException;
  11. import java.io.IOException;
  12. import java.io.InputStreamReader;
  13. import java.io.RandomAccessFile;
  14. import java.net.FileNameMap;
  15. import java.net.URLConnection;
  16. import java.text.ParseException;
  17. import java.text.SimpleDateFormat;
  18. import java.util.Date;
  19. import java.util.Random;
  20. /**
  21. * @Description 文件工具类
  22. */
  23. public class FileUtil {
  24. public static String FILEPATH = "/storage/emulated/0/logdata/";
  25. public static final long SEVENT_DAYS = 604800000;
  26. private static String TAG = "FileUtil";
  27. /**
  28. * 获取指定目录内所有文件路径
  29. *
  30. * @param dirPath 需要查询的文件目录
  31. * @param _type 查询类型,比如mp3
  32. */
  33. public static File[] getAllFiles(String dirPath, String _type) {
  34. File f = new File(dirPath);
  35. if (!f.exists()) {//判断路径是否存在
  36. if (f.mkdir()) {
  37. getAllFiles(dirPath, _type);
  38. }
  39. return null;
  40. }
  41. File[] files = f.listFiles();
  42. if (files == null) {//判断权限
  43. return null;
  44. }
  45. for (File _file : files) {//遍历目录
  46. String _name = _file.getName();
  47. String filePath = _file.getAbsolutePath();//获取文件路径
  48. String fileName = _file.getName().substring(0, _name.length() - 4);//获取文件名
  49. Log.d("LOGCAT", "fileName:" + fileName);
  50. Log.d("LOGCAT", "FILEPATH:" + filePath);
  51. }
  52. return files;
  53. }
  54. /**
  55. * 判断文件是否为图片
  56. *
  57. * @param filePath 路径
  58. * @return
  59. */
  60. public static boolean isImageFile(String filePath) {
  61. BitmapFactory.Options options = new BitmapFactory.Options();
  62. options.inJustDecodeBounds = true;
  63. BitmapFactory.decodeFile(filePath, options);
  64. if (options.outWidth == -1) {
  65. return false;
  66. }
  67. return true;
  68. }
  69. private final static String PREFIX_VIDEO = "video/";
  70. /**
  71. * Get the Mime Type from a File
  72. *
  73. * @param fileName 文件名
  74. * @return 返回MIME类型
  75. * thx https://www.oschina.net/question/571282_223549
  76. * add by fengwenhua 2017年5月3日09:55:01
  77. */
  78. private static String getMimeType(String fileName) {
  79. FileNameMap fileNameMap = URLConnection.getFileNameMap();
  80. String type = fileNameMap.getContentTypeFor(fileName);
  81. return type;
  82. }
  83. /**
  84. * 根据文件后缀名判断 文件是否是视频文件
  85. *
  86. * @param fileName 文件名
  87. * @return 是否是视频文件
  88. */
  89. public static boolean isVedioFile(String fileName) {
  90. String mimeType = getMimeType(fileName);
  91. if (!TextUtils.isEmpty(fileName) && mimeType.contains(PREFIX_VIDEO)) {
  92. return true;
  93. }
  94. return false;
  95. }
  96. public static String getDeviceId() {
  97. String deviceId = "";
  98. File file = new File("/storage/emulated/0/mht/deviceid.txt");
  99. String fileContent = getFileContent(file);
  100. if (file != null && !TextUtils.isEmpty(fileContent)) {
  101. //如果存在 直接获取
  102. Log.e(TAG, "getDeviceId: " + fileContent);
  103. deviceId = fileContent.trim();
  104. } else {
  105. //不存在 先生成再获取
  106. writeData();
  107. deviceId = getFileContent(file).trim();
  108. }
  109. int param = (int) SharedPreferencesUtils.getParam(Name.CONNECT_STATE, 10);
  110. if (param == 2) {
  111. return deviceId;
  112. } else {
  113. return "";
  114. }
  115. }
  116. private static void writeData() {
  117. String filePath = "/storage/emulated/0/mht/";
  118. String fileName = "deviceid.txt";
  119. String deviceId = "";
  120. long l = System.currentTimeMillis();
  121. Random random = new Random();
  122. String randomText = "";
  123. for (int i = 0; i < 4; i++) {
  124. int j = random.nextInt(1000);
  125. randomText = randomText + j;
  126. }
  127. deviceId = String.valueOf(l) + randomText;
  128. writeTxtToFile(deviceId, filePath, fileName);
  129. }
  130. // 将字符串写入到文本文件中
  131. private static void writeTxtToFile(String strcontent, String filePath, String fileName) {
  132. //生成文件夹之后,再生成文件,不然会出错
  133. makeFilePath(filePath, fileName);
  134. String strFilePath = filePath + fileName;
  135. // 每次写入时,都换行写
  136. String strContent = strcontent + "\r\n";
  137. try {
  138. File file = new File(strFilePath);
  139. if (!file.exists()) {
  140. Log.d("TestFile", "Create the file:" + strFilePath);
  141. file.getParentFile().mkdirs();
  142. file.createNewFile();
  143. }
  144. RandomAccessFile raf = new RandomAccessFile(file, "rwd");
  145. raf.seek(file.length());
  146. raf.write(strContent.getBytes());
  147. raf.close();
  148. } catch (Exception e) {
  149. Log.e("TestFile", "Error on write File:" + e);
  150. }
  151. }
  152. //生成文件
  153. private static File makeFilePath(String filePath, String fileName) {
  154. File file = null;
  155. makeRootDirectory(filePath);
  156. try {
  157. file = new File(filePath + fileName);
  158. if (!file.exists()) {
  159. file.createNewFile();
  160. }
  161. } catch (Exception e) {
  162. e.printStackTrace();
  163. }
  164. return file;
  165. }
  166. //生成文件夹
  167. private static void makeRootDirectory(String filePath) {
  168. File file = null;
  169. try {
  170. file = new File(filePath);
  171. if (!file.exists()) {
  172. file.mkdir();
  173. }
  174. } catch (Exception e) {
  175. Log.i("error:", e + "");
  176. }
  177. }
  178. //读取指定目录下的所有TXT文件的文件内容
  179. private static String getFileContent(File file) {
  180. String content = "";
  181. if (!file.isDirectory()) { //检查此路径名的文件是否是一个目录(文件夹)
  182. if (file.getName().endsWith("txt")) {//文件格式为""文件
  183. BufferedReader buffreader = null;
  184. try {
  185. buffreader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
  186. String line = "";
  187. //分行读取
  188. while ((line = buffreader.readLine()) != null) {
  189. content += line + "\n";
  190. }
  191. } catch (java.io.FileNotFoundException e) {
  192. Log.d("TestFile", "The File doesn't not exist.");
  193. } catch (IOException e) {
  194. Log.d("TestFile", e.getMessage());
  195. } finally {
  196. try {
  197. if (buffreader != null) {
  198. buffreader.close();//关闭输入流
  199. }
  200. } catch (IOException e) {
  201. e.printStackTrace();
  202. }
  203. }
  204. }
  205. }
  206. return content;
  207. }
  208. //flie:要删除的文件夹的所在位置
  209. public static void deleteFile(File file) {
  210. if (file.isDirectory()) {
  211. File[] files = file.listFiles();
  212. for (int i = 0; i < files.length; i++) {
  213. File f = files[i];
  214. deleteFile(f);
  215. }
  216. // file.delete();//如要保留文件夹,只删除文件,请注释这行
  217. } else if (file.exists()) {
  218. file.delete();
  219. }
  220. }
  221. /**
  222. * 获取文件后缀名
  223. *
  224. * @param fileName
  225. * @return
  226. */
  227. public static String getFileType(String fileName) {
  228. return fileName.substring(fileName.lastIndexOf(".") + 1);
  229. }
  230. public static Bitmap getLoacalBitmap(String url) {
  231. FileInputStream fis = null;
  232. try {
  233. fis = new FileInputStream(url);
  234. return BitmapFactory.decodeStream(fis); ///把流转化为Bitmap图片
  235. } catch (FileNotFoundException e) {
  236. e.printStackTrace();
  237. return null;
  238. } finally {
  239. if (fis != null) {
  240. try {
  241. fis.close();
  242. } catch (IOException e) {
  243. e.printStackTrace();
  244. }
  245. }
  246. }
  247. }
  248. /**
  249. * 删除超过7天的log文件
  250. */
  251. public static void pastDueLog() {
  252. File logFolder = new File(FILEPATH);
  253. if (logFolder.exists()) {
  254. File[] logFiles = logFolder.listFiles();
  255. for (File file : logFiles) {
  256. SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
  257. String nowDate = format.format(new Date(System.currentTimeMillis()));
  258. //Log.d(TAG, "duibi: " + nowDate);
  259. try {
  260. String replace = file.getName().replace("-" + FileUtil.getDeviceId() + ".txt", "");
  261. Log.d(TAG, "pastDueLog: " + replace);
  262. Date dateFile = format.parse(replace);
  263. Date dataNow = format.parse(nowDate);
  264. long fileTime = dateFile.getTime();
  265. long nowTime = dataNow.getTime();
  266. if (nowTime - fileTime > SEVENT_DAYS) {
  267. //如果超过7天,我们就进行删除指定的文件,否则就什么都不做。
  268. //Log.d(TAG, "duibi: "+fileTime);
  269. //删除
  270. file.delete();
  271. }
  272. //Log.d(TAG, "duibi: "+dataNow);
  273. //Log.d(TAG, "duibi: " + file.getName());
  274. } catch (ParseException e) {
  275. //604800000 7天
  276. e.printStackTrace();
  277. }
  278. }
  279. }
  280. }
  281. /**
  282. * 获取当前时间
  283. *
  284. * @return
  285. */
  286. public static String getFileName() {
  287. SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
  288. String date = format.format(new Date(System.currentTimeMillis())) + "-" + FileUtil.getDeviceId() + ".txt";
  289. return date;
  290. }
  291. /**
  292. * 創建log文件
  293. */
  294. public static File createLogFile() {
  295. return makeFilePath(FILEPATH, FileUtil.getFileName());
  296. }
  297. }