shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
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
package com.walker.infrastructure.utils;
 
import com.walker.infrastructure.core.FileNotFoundException;
import com.walker.infrastructure.core.NestedRuntimeException;
 
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
 
public class FileUtils {
 
    public static final String OS_NAME = "os.name";
    public static final String OS_WINDOWS_NAME = "windows";
    public static final String FILE_SEPARATOR = "/";
    
    /**
     * 缩略图文件名的后缀:_s 表示小图
     */
    public static final String THUMB_SUFFIX = "_s";
    
//    private static final String FILE_ROOT_WINDOWS = "file://";
//    private static final String FILE_ROOT_UNIX = "file:///";
    private static final String FILE_ROOT_WINDOWS = "";
    private static final String FILE_ROOT_UNIX = "/";
 
    /**
     * 从文件路径中,截取文件ID,文件用id命名。
     * @param videoPath 文件绝对路径,如 /opt/ai/video/20220921/landscape_01.mp4 或 d:\demo\movie.jpg
     * @return 返回文件名,没有路径和后缀,如: landscape_01 或 movie
     */
    public static final String getFileNameWithoutSuffix(String videoPath, String suffix){
        // 如果存在windows反斜杠,先转换成正斜杠。2022-10-11
        videoPath = videoPath.replaceAll("\\\\", StringUtils.FOLDER_SEPARATOR);
        String[] array = videoPath.split(StringUtils.FOLDER_SEPARATOR);
        if(array == null || array.length == 0){
            System.out.println("文件名称截取id错误:" + videoPath);
            return null;
        }
        String fileName = array[array.length-1];
//        String[] idValue = fileName.split(".");
        return fileName.replaceAll(suffix, StringUtils.EMPTY_STRING);
    }
 
    /**
     * 返回文件路径地址中的路径部分,如: d:/demo/file.txt --> d:/demo/
     * @param url
     * @return
     * @date 2023-02-15
     */
    public static final String getFilePathWithoutName(String url){
        if(StringUtils.isEmpty(url)){
            return null;
        }
        int lastSeparatorIndex = url.lastIndexOf(StringUtils.FOLDER_SEPARATOR);
        if(lastSeparatorIndex < 0){
            System.out.println("url中不包含文件路径:" + url);
            return null;
        }
        return url.substring(0, lastSeparatorIndex);
    }
 
    /**
     * 返回路径中文件名,如: d:/demo/file.txt --> file.txt
     * @param url
     * @return
     */
    public static final String getFileNameWithoutPath(String url){
        int fileNameIndex = url.lastIndexOf(StringUtils.FOLDER_SEPARATOR) + 1;
        if(fileNameIndex < 0){
            System.out.println("url中不包含文件路径:" + url);
            return null;
        }
        return url.substring(fileNameIndex, url.length());
    }
 
    /**
     * 文件夹或文件是否存在。
     * @param fileOrFolder 文件(或文件夹)绝对路径
     * @return
     * @date 2022-10-11
     */
    public static final boolean isExist(String fileOrFolder){
        if(StringUtils.isEmpty(fileOrFolder)){
            return false;
        }
        File file = new File(fileOrFolder);
        return file.exists();
    }
 
    public static final boolean isWindows(){
        String osName = System.getProperty(OS_NAME);
        if(osName != null && osName.toLowerCase().indexOf(OS_WINDOWS_NAME) >= 0){
            return true;
        }
        return false;
    }
    
    public static final String getFileSystemRoot(){
        if(isWindows()){
            return FILE_ROOT_WINDOWS;
        } else
            return FILE_ROOT_UNIX;
    }
    
    /**
     * 检查目录,如果不存在将会创建新目录,包括子目录。
     * @param path
     */
    public static final void checkDir(String path){
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
    }
    
    private static final String FILE_EXT_SEPARATOR = ".";
    
    /**
     * 返回文件名的扩展名,如果不存在返回<code>null</code>,如: txt
     * @param filename
     * @return
     */
    public static final String getFileExt(String filename){
        int extIndex = filename.lastIndexOf(FILE_EXT_SEPARATOR);
        if(extIndex > 0){
            // filename.txt
            return filename.substring(extIndex + 1);
        }
        return null;
    }
    
    /**
     * 返回文件字节信息,通常适用于读取较小文件。
     * @param file
     * @return
     */
    public static final byte[] getFileBytes(File file){
        assert (file != null);
        InputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(file));
//            int byteCount = 0;
            byte[] buffer = new byte[in.available()];
//            int bytesRead = -1;
//            while ((bytesRead = in.read(buffer)) != -1) {
//                byteCount += bytesRead;
//            }
            in.read(buffer, 0, buffer.length);
            return buffer;
            
        } catch (java.io.FileNotFoundException e) {
            throw new FileNotFoundException();
        } catch(IOException ioe){
            throw new NestedRuntimeException(null, ioe);
        } finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {}
            }
        }
    }
 
    /**
     * 读文本内容,按行读取,返回集合。
     * @param filePath 文件绝对路径
     * @return
     */
    public static List<String> getFileLines(String filePath){
        File file = new File(filePath);
        if(!file.exists()){
            System.out.println("文件不存在,无法读取内容:" + filePath);
            return null;
        }
//        String encoding = "utf-8";
        List<String> content = new ArrayList<>(64);
        try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), StringUtils.DEFAULT_CHARSET_UTF8);
             BufferedReader bufferedReader = new BufferedReader(read)) {
            //判断文件是否存在
            if (file.isFile() && file.exists()) {
                String lineTxt;
                while ((lineTxt = bufferedReader.readLine()) != null) {
//                    System.out.println(lineTxt);
                    content.add(lineTxt);
                }
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("读取文件内容出错");
        }
        return content;
    }
    
    public static final void writeFile(byte[] content, String filename){
        throw new UnsupportedOperationException();
    }
    
    /**
     * 删除一个文件
     * @param file 文件(不能是目录)
     * @return
     */
    public static final boolean deleteFile(File file){
        if(file != null){
            try{
                if(file.isDirectory()){
                    throw new UnsupportedOperationException("File must be not a directory!");
                }
                return file.delete();
            } catch(Exception e){
                throw new NestedRuntimeException(null, e);
            }
        }
        return false;
    }
    
    /**
     * 把字符串内容写入到一个文件中。
     * @param content
     * @param fileName
     * @return
     * @throws Exception
     */
    public static boolean writeTxtFile(String content,File fileName)throws Exception{  
        RandomAccessFile mm=null;  
        boolean flag=false;  
//        FileOutputStream o=null;  
        try {  
//            o = new FileOutputStream(fileName);  
//            o.write(content.getBytes("GBK"));  
//            o.close();  
            mm=new RandomAccessFile(fileName,"rw");  
            mm.writeBytes(content);  
            flag=true;  
        } catch (java.io.FileNotFoundException e) {  
            throw new FileNotFoundException("not found file: " + fileName, e);
        }finally{  
            if(mm!=null){  
                mm.close();  
            }  
        }  
        return flag;  
    }
    
    /**
     * 创建空文件
     * @param filepath
     * @throws IOException
     */
    public static final void createEmptyFile(String filepath) throws IOException{
        File file = new File(filepath);
        if(!file.exists()){
            file.createNewFile();
        } else
            System.out.println("file exist: " + filepath);
    }
    
    /**
     * 给定文件相对路径,返回缩略图路径,如:2014/3/aaa_123456_s.jpg
     * @param path
     * @param ext
     * @return
     */
    @Deprecated
    public static final String getThumbNailsName(String path, String ext){
        StringBuilder thumb = new StringBuilder();
        thumb.append(path.subSequence(0, path.lastIndexOf(StringUtils.SYMBOL_DOT)));
        thumb.append("_s.").append(ext);
        return thumb.toString();
    }
    
    /**
     * 给定文件相对路径,返回缩略图路径,如:2014/3/aaa_123456_s.jpg
     * @param path
     * @return
     */
    public static final String getThumbNailsName(String path){
        StringBuilder thumb = new StringBuilder();
        thumb.append(path.subSequence(0, path.lastIndexOf(StringUtils.SYMBOL_DOT)));
        thumb.append("_s.").append(FileUtils.getFileExt(path));
        return thumb.toString();
    }
    
    public static void main(String[] args){
//        System.out.println(FileUtils.getFileExt("myfile.txt"));
//        System.out.println(FileUtils.getFileExt("myfile-111.2012.txt"));
//        System.out.println(FileUtils.getFileExt("myfiletxt"));
//        System.out.println("file: " + FileUtils.getFileBytes(new File("d:/sso-1.jpg")));
//        System.out.println(getThumbNailsName("2014/3/aaa_123456.jpg"));
//        System.out.println(getFileExt("d:/test/demo.jpg"));
        System.out.println(getFilePathWithoutName("d:/test/demo.jpg"));
        System.out.println(getFileNameWithoutPath("d:/test/demo.jpg"));
    }
}