admin
2022-01-28 cd7767932dddeaf6d9c73a83d4a9b38f0341b77f
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
package com.yeshi.buwan.util;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
 
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.servlet.http.HttpServletRequest;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 
import com.yeshi.buwan.domain.FileName;
import com.yeshi.buwan.service.imp.VideoManager;
 
//文件处理
@Entity
public class FileUtil {
    public final static int TYPE_PICTURE_CLASS = 1;// 分类图标文件夹
    public final static int TYPE_PICTURE_HOME_AD = 2;// 广告图片
    public final static int TYPE_PICTURE_VIDEO = 3;// 视频图片文件
    public final static int TYPE_PICTURE_STAR = 4;// 明星头像
    @Id
    @GeneratedValue
    public final static int TYPE_VIDEO = 5;// 视频文件
    public final static String PROJECT_NAME = "BuWan";
 
    /**
     * 上传头像
     *
     * @param type
     * @param request
     * @return
     */
    public List<String> getFile(int type, HttpServletRequest request) throws Exception {
        List<String> resltList = new ArrayList<String>();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 获取文件需要上传到的路径
        String path = request.getRealPath("/upload");
 
        // 如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
        // 设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
        /**
         * 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem
         * 格式的 然后再将其真正写到 对应目录的硬盘上
         */
        factory.setRepository(new File(path));
        // 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
        factory.setSizeThreshold(1024 * 1024);
 
        // 高水平的API文件上传处理
        ServletFileUpload upload = new ServletFileUpload(factory);
 
        try {
            // 可以上传多个文件
            List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
 
            for (FileItem item : list) {
                // 获取表单的属性名字
                String name = item.getFieldName();
 
                // 如果获取的 表单信息是普通的 文本 信息
                if (item.isFormField()) {
 
                }
                // 对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些
                else {
                    /**
                     * 以下三步,主要获取 上传文件的名字
                     */
                    // 获取路径名
                    String value = item.getName();
                    // 索引到最后一个反斜杠
                    int start = value.lastIndexOf("\\");
                    // 截取 上传文件的 字符串名字,加1是 去掉反斜杠,
                    String filename = value.substring(start + 1);
 
                    request.setAttribute(name, filename);
 
                    File file = new File(path);
 
                    if (!file.exists())
                        file.mkdirs();
 
                    File f = new File(createFile(type, path), filename);
 
                    resltList.add(f.getPath().split("webapps")[1]);
 
                    OutputStream out = new FileOutputStream(f);
 
                    InputStream in = item.getInputStream();
 
                    int length = 0;
                    byte[] buf = new byte[1024];
 
                    LogUtil.i("获取上传文件的总共的容量:" + item.getSize());
 
                    // in.read(buf) 每次读到的数据存放在 buf 数组中
                    while ((length = in.read(buf)) != -1) {
                        // 在 buf 数组中 取出数据 写到 (输出流)磁盘上
                        out.write(buf, 0, length);
                    }
 
                    in.close();
                    out.close();
                }
            }
 
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return resltList;
    }
 
    public Map<String, String> getTextAndFile(int type, HttpServletRequest request) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        DiskFileItemFactory factory = new DiskFileItemFactory();
 
        // 获取文件需要上传到的路径
        String path = request.getRealPath("/upload");
 
        // 如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
        // 设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
        /**
         * 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem
         * 格式的 然后再将其真正写到 对应目录的硬盘上
         */
        factory.setRepository(new File(path));
        // 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
        factory.setSizeThreshold(1024 * 1024);
 
        // 高水平的API文件上传处理
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
 
        // 可以上传多个文件
        List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
        for (FileItem item : list) {
            // 获取表单的属性名字
            String name = item.getFieldName();
 
            // 如果获取的 表单信息是普通的 文本 信息
            if (item.isFormField()) {
                // String value = new String(item.getString().getBytes(),
                // "UTF-8");
                map.put(name, item.getString("UTF-8"));
            }
            // 对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些
            else {
                /**
                 * 以下三步,主要获取 上传文件的名字
                 */
                // 获取路径名
                String value = item.getName();
                if (StringUtil.isNullOrEmpty(value))
                    continue;
                // 索引到最后一个反斜杠
                int start = value.lastIndexOf("\\");
                // .需要转义
                String end = value.split("\\.")[1];
                // 截取 上传文件的 字符串名字,加1是 去掉反斜杠,
                String filename = "";
                if (value.contains(".") && value.length() > 2) {
                    filename = System.currentTimeMillis() + (int) (Math.random() * 10000) + "." + end;
                    request.setAttribute(name, filename);
                }
                File file = new File(path);
 
                if (!file.exists())
                    file.mkdirs();
 
                String createFile = createFile(type, path);
                File f = new File(createFile, filename);
 
                String fileName = createFile.split(PROJECT_NAME)[1] + File.separator + filename;
                fileName = fileName.replace("\\", "/");
                map.put(name, fileName);
 
                OutputStream out = new FileOutputStream(f);
 
                InputStream in = item.getInputStream();
 
                int length = 0;
                byte[] buf = new byte[1024];
 
                LogUtil.i("获取上传文件的总共的容量:" + item.getSize());
 
                // in.read(buf) 每次读到的数据存放在 buf 数组中
                while ((length = in.read(buf)) != -1) {
                    // 在 buf 数组中 取出数据 写到 (输出流)磁盘上
                    out.write(buf, 0, length);
                }
 
                in.close();
                out.close();
            }
        }
 
        return map;
    }
 
    // 创建文件夹
    private String createFile(int type, String path) {
        if (type == TYPE_PICTURE_CLASS)// 分类图片
        {
            File f = new File(path, "class");
            if (!f.exists())
                f.mkdirs();
            return f.getPath();
        } else if (type == TYPE_PICTURE_HOME_AD)// 首页广告图片
        {
            File f = new File(path, "ad");
            if (!f.exists())
                f.mkdirs();
            return f.getPath();
        } else if (type == TYPE_PICTURE_STAR)// 明星头像
        {
            File ff = new File(path, "star");
            if (!ff.exists())
                ff.mkdirs();
            File f = new File(ff.getPath(), "picture");
            if (!f.exists())
                f.mkdirs();
            return f.getPath();
        } else if (type == TYPE_PICTURE_VIDEO)// 视频封面
        {
            File ff = new File(path, "juhe");
            if (!ff.exists())
                ff.mkdirs();
            File f = new File(ff.getPath(), "picture");
            if (!f.exists())
                f.mkdirs();
            return f.getPath();
        } else if (type == TYPE_VIDEO)// 视频封面
        {
            File ff = new File(path, "juhe");
            if (!ff.exists())
                ff.mkdirs();
            File f = new File(ff.getPath(), "juhe");
            if (!f.exists())
                f.mkdirs();
            return f.getPath();
        }
        return "";
 
    }
 
    public static String getAbsolutePathWithProjectName(HttpServletRequest request, String path) {
        return "http://" + request.getLocalAddr() + ":" + request.getLocalPort() + path;
    }
 
    public static void downFile(String urlStr, String filePath) throws MalformedURLException {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;
 
        URL url = new URL(urlStr);
 
        try {
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream(filePath);
 
            byte[] buffer = new byte[1204];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                LogUtil.i(bytesum);
                fs.write(buffer, 0, byteread);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    // 复制文件
    public static boolean copyFile(String fileFrom, String fileTo) {
        try {
            File f = new File(fileTo);
            if (!f.exists())
                f.createNewFile();
 
            FileInputStream in = new java.io.FileInputStream(fileFrom);
            FileOutputStream out = new FileOutputStream(fileTo);
            byte[] bt = new byte[1024];
            int count;
            while ((count = in.read(bt)) > 0) {
                out.write(bt, 0, count);
            }
            in.close();
            out.close();
            return true;
        } catch (IOException ex) {
            return false;
        }
    }
 
    public static boolean save(String ht, String path) throws IOException {
        try {
            File f = new File(path);
            if (!f.exists())
                f.createNewFile();
            FileWriter writer;
            writer = new FileWriter(path);
            writer.write(ht);
            writer.flush();
            writer.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
 
    public static List<FileName> reNameFile(String dir, String path) {
        if (dir.endsWith("/"))
            dir = dir.substring(0, dir.length() - 1);
        VideoManager manager = new VideoManager();
        List<FileName> list = new ArrayList<FileName>();
        if (!StringUtil.isNullOrEmpty(dir))
            if (StringUtil.isNullOrEmpty(path)) {// 获取文件夹下面的所有文件
                File f = new File(dir);
                File[] fileList = f.listFiles();
                if (fileList.length > 0) {
                    String[] sts = fileList[0].getPath().split("\\.");
 
                    for (int i = 0; i < fileList.length; i++) {
                        String[] files = fileList[i].getPath().split("/");
                        FileName name = new FileName();
                        name.setNewName(
                                dir + "/" + manager.getVideoPathName(sts[sts.length - 1], files[files.length - 1]));
                        name.setOldName(files[files.length - 1]);
                        list.add(name);
                        fileList[i].renameTo(new File(list.get(i).getNewName()));
                        LogUtil.i(name.getOldName());
                        LogUtil.i(name.getNewName());
                    }
                }
            } else {// 获取某一个文件
                String[] sts = path.split("\\.");
                String newPath = dir + "/" + manager.getVideoPathName(sts[sts.length - 1], path);
                new File(dir + "/" + path).renameTo(new File(newPath));
                FileName name = new FileName();
                name.setNewName(newPath);
                name.setOldName(path);
                list.add(name);
            }
        return list;
    }
 
    public static List<String> readText(String filepath) throws IOException {
        List<String> list = new ArrayList<String>();
        // String path = "C:/Users/Administrator/Desktop/乐视云/1234.txt";// 相对路径
        File filename = new File(filepath);
        BufferedReader bufread = new BufferedReader(new FileReader(filename));
        String read;
        while ((read = bufread.readLine()) != null) {
            LogUtil.i(read);
            list.add(read);
            // readStr = (readStr + read);
        }
        // LogUtil.i("读取配置文件信息:" + readStr);
        return list;
    }
 
    public static String readTxt(String filepath) throws IOException {
        String result = "";
        File filename = new File(filepath);
        BufferedReader bufread = new BufferedReader(new FileReader(filename));
        String read;
        while ((read = bufread.readLine()) != null) {
            LogUtil.i(read);
            result += read;
            // readStr = (readStr + read);
        }
        // LogUtil.i("读取配置文件信息:" + readStr);
        return result;
    }
 
    public static String saveAsFile(InputStream inputStream, String path) throws IOException {
        if (!new File(path).exists()) {
            new File(path).createNewFile();
        }
 
        FileOutputStream fileOut = new FileOutputStream(new File(path));
        byte[] buf = new byte[1024 * 8];
        while (true) {
            int read = 0;
            if (inputStream != null) {
                read = inputStream.read(buf);
            }
            if (read == -1) {
                break;
            }
            fileOut.write(buf, 0, read);
        }
        fileOut.close();
        return path;
    }
 
    public static String getCacheDir() {
 
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            File f = new File("D:/cache");
            if (!f.exists())
                f.mkdirs();
            return f.getPath();
        } else {
            File f = new File("/usr/local/cache");
            if (!f.exists())
                f.mkdirs();
            return f.getPath();
        }
    }
 
 
 
 
 
}