FileUtil.java
14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
package com.drp.mobliemall.utils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import com.drp.mobliemall.config.SysConstant;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by xiniu_wutao on 15/6/30.
* <p>
* 文件操作类
*/
public class FileUtil {
public static String SDCardRoot;
public static File updateFile;
static {
// 获取SD卡路径
SDCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
}
/**
* 创建文件夹
*
* @throws IOException
*/
public static File createFileInSDCard(String fileName, String dir) {
File file = new File(SDCardRoot + dir + File.separator + fileName);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
updateFile = file;
return file;
}
/**
* 创建目录
*
* @param dir
* @return
*/
public static File creatSDDir(String dir) {
File dirFile = new File(SDCardRoot + dir + File.separator);
dirFile.mkdirs();
return dirFile;
}
/**
* 检测文件是否存在
*/
public static boolean isFileExist(String fileName, String path) {
File file = new File(SDCardRoot + path + File.separator + fileName);
return file.exists();
}
public static boolean isFileExist(String filePath) {
File file = new File(filePath);
return file.exists();
}
/**
* 通过流往文件里写东西
*/
public static File writeToSDFromInput(String path, String fileName, InputStream input) {
File file = null;
OutputStream output = null;
try {
file = createFileInSDCard(fileName, path);
output = new FileOutputStream(file, false);
byte buffer[] = new byte[4 * 1024];
int temp;
while ((temp = input.read(buffer)) != -1) {
output.write(buffer, 0, temp);
}
output.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
/**
* 把字符串写入文件
*/
public static File writeToSDFromInput(String path, String fileName, String data) {
File file = null;
OutputStreamWriter outputWriter = null;
OutputStream outputStream = null;
try {
creatSDDir(path);
file = createFileInSDCard(fileName, path);
outputStream = new FileOutputStream(file, false);
outputWriter = new OutputStreamWriter(outputStream);
outputWriter.write(data);
outputWriter.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
public static String getFromCipherConnection(String actionUrl, String content, String path) {
try {
File[] files = new File[1];
files[0] = new File(path);
// content = CipherUtil.getCipherString(content);
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(5 * 1000); // 缓存的最长时间
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"userName\"" + LINEND);// \"userName\"
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(content);
sb.append(LINEND);
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
// 发送文件数据
if (files != null) {
for (File file : files) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"" + file.getName()
+ "\"; filename=\"" + file.getName() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET
+ LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
try {
InputStream is = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
outStream.close();
// 得到响应码
int res = conn.getResponseCode();
if (res == 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(
(InputStream) conn.getInputStream()));
String line = null;
StringBuilder result = new StringBuilder();
while ((line = in.readLine()) != null) {
result.append(line);
}
in.close();
conn.disconnect();// 断开连接
return "true";
} else {
return "";
}
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
public static byte[] getFileContent(String fileName) {
FileInputStream fin = null;
try {
fin = new FileInputStream(fileName);
int length = fin.available();
byte[] bytes = new byte[length];
fin.read(bytes);
return bytes;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (fin != null) {
fin.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @param file
* @Description 删除文件或文件夹
*/
public static void delete(File file) {
if (!file.exists()) {
return; // 不存在直接返回
}
if (file.isFile()) {
file.delete(); // 若是文件则删除后返回
return;
}
// 若是目录递归删除后,并最后删除目录后返回
if (file.isDirectory()) {
File[] childFiles = file.listFiles();
if (childFiles == null || childFiles.length == 0) {
file.delete(); // 如果是空目录,直接删除
return;
}
for (int i = 0; i < childFiles.length; i++) {
delete(childFiles[i]); // 递归删除子文件或子文件夹
}
file.delete(); // 删除最后的空目录
}
return;
}
/**
* @param dirFile 目录文件
* @param timeLine 时间分隔线
* @Description 删除目录下过旧的文件
*/
public static void deleteHistoryFiles(File dirFile, long timeLine) {
// 不存在或是文件直接返回
if (!dirFile.exists() || dirFile.isFile()) {
return;
}
try {
// 如果是目录则删除过旧的文件
if (dirFile.isDirectory()) {
File[] childFiles = dirFile.listFiles();
if (childFiles == null || childFiles.length == 0) {
return; // 如果是空目录就直接返回
}
// 遍历文件,删除过旧的文件
Long fileTime;
for (int i = 0; i < childFiles.length; i++) {
fileTime = childFiles[i].lastModified();
if (fileTime < timeLine) {
delete(childFiles[i]);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static File save2File(String savePath, String saveName,
String crashReport) {
try {
File dir = new File(savePath);
if (!dir.exists())
dir.mkdir();
File file = new File(dir, saveName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(crashReport.toString().getBytes());
fos.close();
return file;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String saveAudioResourceToFile(byte[] content, int userId) {
try {
String audioSavePath = CommonUtil.getAudioSavePath(userId);
File file = new File(audioSavePath);
FileOutputStream fops = new FileOutputStream(file);
fops.write(content);
fops.flush();
fops.close();
return audioSavePath;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String saveGifResourceToFile(byte[] content) {
try {
String gifSavePath = CommonUtil.getSavePath(SysConstant.FILE_SAVE_TYPE_IMAGE);
File file = new File(gifSavePath);
FileOutputStream fops = new FileOutputStream(file);
fops.write(content);
fops.flush();
fops.close();
return gifSavePath;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@SuppressWarnings("unused")
private static Bitmap getBitmap(InputStream fs) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 1;
Bitmap imgBitmap = BitmapFactory.decodeStream(fs, null, opts);
if (imgBitmap != null) {
int width = imgBitmap.getWidth();
int height = imgBitmap.getHeight();
imgBitmap = Bitmap.createScaledBitmap(imgBitmap, width, height,
true);
}
return imgBitmap;
}
public static long getFileLen(File file) {
long total = 0;
try {
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
total += len;
}
is.close();
} catch (Exception e) {
}
return total;
}
public static boolean isSdCardAvailuable() {
boolean bRet = false;
do {
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
break;
}
if (CommonUtil.getSDFreeSize() < 5) {
break;
}
bRet = true;
} while (false);
return bRet;
}
public static byte[] InputStreamToByte(InputStream is) throws IOException {
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1) {
bytestream.write(ch);
}
byte imgdata[] = bytestream.toByteArray();
bytestream.close();
return imgdata;
}
public static byte[] File2byte(String filePath) {
byte[] buffer = null;
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
public static String getExtensionName(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length() - 1))) {
return filename.substring(dot + 1);
}
}
return filename;
}
}