본문 바로가기
Developer/Java

[Java] FileUtil.java

by 순수한소년 2023. 8. 10.
728x90
반응형

@

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
package test.core.util;
 
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFilePermission;
import java.util.HashSet;
import java.util.Set;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
 
import wevenjv.core.exception.FileUtilException;
 
public class FileUtil 
{
    static Logger logger = LoggerFactory.getLogger(FileUtil.class);
    
    public static String[] imageUpload( MultipartFile file, String uploadRealPath, boolean isCreateThumbnail ) throws IllegalStateException, IOException
    {
        // 경로
        int pathPos = uploadRealPath.lastIndexOf"/" );
        String path = uploadRealPath.substring0, pathPos );
        File pathData = new File( path );
        
        //해당 디렉토리의 존재여부를 확인
        if(!pathData.exists()){
            //없다면 생성
            if (pathData.mkdirs()){
              logger.debug("디렉토리 생성 성공");
            }else{
              System.out.println("디렉토리 생성 실패");
            }
        }
        
        File fileData = new File(uploadRealPath);
 
        if( fileData.exists() ){
            if( fileData.isDirectory() ){
                throw new FileUtilException("이미 존재하는 디렉토리와 이름이 같습니다. ", FileUtilException.ERROR_CODE_NOT_FILE);
            }else if( fileData.isFile() ){
                fileData.deleteOnExit();
            }
        }
        
        file.transferTo(fileData);
        
        return new String[]{"thumb"};
    }    
        
    /**
     * @param file
     * @param uploadRealPath
     * @param isOverride
     * @throws IOException 
     * @throws IllegalStateException 
     * @throws FileUtilException 
     */
    public static String upload(MultipartFile file, String uploadRealPath, boolean isOverride)
            throws IllegalStateException, IOException, FileUtilException
    {
        // 경로
        int pathPos = uploadRealPath.lastIndexOf"/" );
        String path = uploadRealPath.substring0, pathPos );
        File pathData = new File( path );
        
        //해당 디렉토리의 존재여부를 확인
        if(!pathData.exists()){
            //없다면 생성
            if (pathData.mkdirs()){
                logger.debug("디렉토리 생성 성공");
            }else{
                logger.debug("디렉토리 생성 실패");
            }
        }
        
        File fileData = new File(uploadRealPath);
        
        int count = 0;
        int pos = uploadRealPath.lastIndexOf"." );
        String ext = null;
        String fileNameExcludeExt = null;
        // [hanjd] 파일명에 .이 없는 경우가 있을 수 있음.
        // > UUID 형식의 파일명의 경우 . 을 포함하지 않는다.
        if(pos < 0){
            ext = "";
            fileNameExcludeExt = uploadRealPath; 
        }else{
            ext = uploadRealPath.substring( pos + 1 );
            fileNameExcludeExt = uploadRealPath.substring0, pos-1 ); 
        }
 
        if( fileData.exists() ){
            if( fileData.isFile() ){
                if( isOverride ){
                    fileData.deleteOnExit();
                }else{
                    while( fileData.exists() ){
                        uploadRealPath = fileNameExcludeExt + "(" + count + ")." + ext;
                        fileData = new File(uploadRealPath);
                        
                        count++;
                    }
                    file.transferTo(fileData);
                }
                
            }else if( fileData.isDirectory() ){
                while( fileData.exists() ){
                    uploadRealPath = fileNameExcludeExt + "(" + count + ")." + ext;
                    fileData = new File(uploadRealPath);
                    
                    count++;
                }
                file.transferTo(fileData);
            }
        }else{
            file.transferTo(fileData);
        }
        
        String fileServerName = uploadRealPath.substring( uploadRealPath.lastIndexOf"/" ) + 1 );
        return fileServerName;
    }
    
    public static void delete(String deleteRealPath)
    {
        // 경로
        File fileData = new File(deleteRealPath);
        
        // 파일 존재 여부
        if(fileData.exists()){
            if(fileData.isDirectory()){
                try {
                    FileUtils.deleteDirectory(fileData);
                    logger.debug("delete directory :: {}", deleteRealPath);
                } catch (IOException e) {
                    logger.debug("네트워크 오류");
                }
            }else{
                if(fileData.delete()){
                    logger.debug("SUCCESS!! delete file :: {}", deleteRealPath);
                }else{
                    logger.debug("FAIL!! delete file :: {}", deleteRealPath);
                }
            }
        }
    }
    
    public static void download( HttpServletRequest request, HttpServletResponse response, String fileName, String uploadedRealPath, long fileSize ) throws IOException {
        
        String downName = fileName;
        String browser = request.getHeader("User-Agent");
        if(browser.contains("MSIE"|| browser.contains("Trident")) { 
            downName = URLEncoder.encode(fileName,"UTF-8").replaceAll("\\+""%20"); 
        } else if(browser.contains("Chrome")) {
            StringBuffer sb = new StringBuffer();
 
            for (int i = 0; i < downName.length(); i++) {
                   char c = downName.charAt(i);
                   if (c > '~') {
                         sb.append(URLEncoder.encode("" + c, "UTF-8"));
                   } else {
                         sb.append(c);
                   }
            }
            downName = sb.toString();
        } else { 
            downName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1"); 
        }
        response.setHeader("Content-Disposition","attachment;filename=\"" + downName + "\"");    
        response.setContentType("application/octer-stream"); 
        response.setHeader("Content-Transfer-Encoding""binary;");
 
//        String name = new String( (fileName).getBytes("UTF-8"),"UTF-8" );
//        response.setContentType( request.getSession().getServletContext().getMimeType( uploadedRealPath ) );
//        response.setCharacterEncoding("UTF-8");
//        response.setHeader( "Content-Disposition", "attachment;filename=" + '"' + URLEncoder.encode(name, "UTF-8") + '"');
//        response.setHeader( "Content-Description", "Weven Generated Data" );
        
        File file = null;
        FileInputStream fileIn = null;
        ServletOutputStream out = null;
        
        try {
            file = new File( uploadedRealPath );
            fileIn = new FileInputStream(file);
            out = response.getOutputStream();
            
            byte b [] = new byte[1024]; 
            int data = 0
            while((data=(fileIn.read(b, 0, b.length))) != -1) { 
                out.write(b, 0, data); 
            } 
            out.flush();
        } catch (IOException e) {
            logger.debug("파일 다운로드 에러");
        } finally{
            if(out != null){
                out.close();
                out = null;
            }
            if(fileIn != null){
                fileIn.close();
                fileIn = null;
            }
        }
        
        //copy binary contect to output stream
//        byte[] outputByte = new byte[4096];
//        int readLen;
//        while((readLen=fileIn.read(outputByte)) != -1) {
//            out.write(outputByte, 0, readLen);
//        }
//        fileIn.close();
//        out.flush();
//        out.close();
    }
    
    static public boolean createFileBytes(String path, String fileName, byte[] content){
        FileUtil.createDir(path);
        
        File file = new File(path+"/"+fileName);
        FileOutputStream out = null;
        try{
            if(file.exists() == false){
                if(file.createNewFile() == false){
                    return false;
                }
            }
            
            out = new FileOutputStream(file);
            out.write(content);
            out.close();
            
            setDefaultPermissions(file);
            
            return true;
        }catch(Exception e){
            logger.debug("Error : FileUtil.createFileBytes");
            return false;
        }finally {
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    logger.debug("네트워크 오류");
                }
            }
        }
    }
 
    static public boolean createFileWithUTF8(String path, String fileName, String content){
        return createFileWithEncoding(path, fileName, content, StandardCharsets.UTF_8);
    }
 
    static public boolean createFileWithEncoding(String path, String fileName, String content, Charset charset){
        
        FileUtil.createDir(path);
        
        File file = new File(path+"/"+fileName);
        BufferedWriter out = null;
        try{
            if(file.exists() == false){
                if(file.createNewFile() == false){
                    return false;
                }
            }
            
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
            out.write(content);
            out.close();
            
            setDefaultPermissions(file);
            
            return true;
        }catch(Exception e){
            logger.debug("Error : FileUtil.createFileWithEncoding");
            return false;
        }finally {
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    logger.debug("네트워크 오류");
                }
            }
        }
    }
    
    static public boolean createDir(String path){
        File file = new File(path);
        if(file.exists() == false){
            boolean result = file.mkdirs();
            
            setDefaultPermissions(file);
            
            return result;
        }
        return true;
    }
    
    private static void setDefaultPermissions(File file){
         Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
         perms.add(PosixFilePermission.OWNER_READ);
         perms.add(PosixFilePermission.OWNER_WRITE);
         perms.add(PosixFilePermission.OWNER_EXECUTE);
         perms.add(PosixFilePermission.GROUP_EXECUTE);
         perms.add(PosixFilePermission.GROUP_READ);
         perms.add(PosixFilePermission.OTHERS_EXECUTE);
         perms.add(PosixFilePermission.OTHERS_READ);
         try{
             Files.setPosixFilePermissions(file.toPath(), perms);
         }catch(IOException e){
             logger.debug("네트워크 오류");
         }catch(UnsupportedOperationException e){
             logger.debug("권한 오류");
         }
    }
    
    public static boolean smartCopy(String oldPath, String newPath) {
        try {
            logger.debug("smartCopy :: from {} to {}", oldPath, newPath);
            FileUtils.copyDirectory(new File(oldPath), new File(newPath));
            return true;
        } catch (IOException e) {
            logger.debug("네트워크 오류");
            return false;
        }
    }    
    
    /**
     * 폴더내 모든 파일 호출
     * @param pathname
     * @return
     */
    public static File[] readFilesOnFolder( File directory ){
        return FileUtils.convertFileCollectionToFileArray( FileUtils.listFiles(directory, FileFilterUtils.notFileFilter(DirectoryFileFilter.INSTANCE), FileFilterUtils.notFileFilter(DirectoryFileFilter.INSTANCE)) );
    }
    
    /**
     * 폴더내 모든 파일 호출
     * @param pathname
     * @return
     */
    public static File[] readFilesOnFolder( String pathname ){
        return readFilesOnFolder( new File(pathname) );
    }
    
    /**
     * 확장자 리스트의 것들만 뽑아서 재귀적 호출
     * @param pathname
     * @param extensions
     * @param recursive
     * @return
     */
    public static File[] readFilesOnFolder( String pathname, String[] extensions, boolean recursive ){
        File directory = new File(pathname);
        return FileUtils.convertFileCollectionToFileArray( FileUtils.listFiles(directory, extensions, recursive) );
    }
        
    public static String getNameReal( File file ){
        String originFilePath = file.getName();
        return originFilePath.substring( originFilePath.lastIndexOf("/")+1 );
    }
        
    public static void renameFileOrFolder(File srcFile, String destName, boolean isDirectory ) {
        String originFilePath = srcFile.getAbsolutePath();
        originFilePath = originFilePath.substring(0, originFilePath.indexOf( srcFile.getName() ) );
        if( isDirectory ){
            
            try {
                FileUtils.moveDirectory( srcFile, new File( originFilePath + destName ) );
            } catch (IOException e) {
                logger.debug("네트워크 오류");
            }
        }else{
            try {
                FileUtils.moveFile(srcFile, new File( originFilePath + destName ) );
            } catch (IOException e) {
                logger.debug("네트워크 오류");
            }
        }
    }
    
    public static String readFileToString(File file){
        try {
            return FileUtils.readFileToString(file);
        } catch (IOException e) {
            logger.debug("네트워크 오류");
        }
        return null;
    }
        
    public static void writeStringToFile(File file, String data){
        try {
            FileUtils.writeStringToFile(file, data);
        } catch (IOException e) {
            logger.debug("네트워크 오류");
        }
    }
}
 
cs

@

 

728x90
반응형