xuxiuxi
2017-07-20 8696a36fbb05d376e6cbaba5814419f2a250ba4f
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
package cn.com.basic.face.util;
 
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
 
import cn.com.basic.face.base.MainActivity;
 
public class FileUtil {
 
 
    public static File writeToFile(String fileName, byte[] fileBytes) {
        try {
            return writeToFile(fileName, fileBytes, 0, fileBytes.length);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
 
    public static File writeToFile(String fileName, byte[] fileBytes, int offset, int size) {
        try {
            if (fileBytes == null) {
                fileBytes = new byte[]{};
            }
            String dir = MainActivity.getInstance().getFilesDir().getAbsolutePath();
 
            File file = new File(dir, fileName);
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(dir, fileName)));
            bos.write(fileBytes, offset, size);
            bos.flush();
            bos.close();
            return new File(dir, fileName);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    public static File getFile(String shortFileName) {
        String dir = MainActivity.getInstance().getFilesDir().getAbsolutePath();
        return new File(dir, shortFileName);
    }
 
 
    public static byte[] readFile(File file) {
        // Open file
        RandomAccessFile f = null;
        try {
            f = new RandomAccessFile(file, "r");
            // Get and check length
            long longlength = f.length();
            int length = (int) longlength;
            if (length != longlength)
                throw new IOException("File size >= 2 GB");
            // Read file and return data
            byte[] data = new byte[length];
            f.readFully(data);
            return data;
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                f.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new byte[]{};
    }
 
 
}