服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java文件读写工具类分享

java文件读写工具类分享

2021-03-30 11:24漂流的老妖怪 Java教程

这篇文章主要为大家详细介绍了java文件读写工具类,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了java文件读写工具类的具体代码,供大家参考,具体内容如下

?
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
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
 
import javax.servlet.http.HttpServletResponse;
 
/**
 * <p>文件操作工具类<p>
 * @version 1.0
 * @author li_hao
 * @date 2017年1月18日
 */
@SuppressWarnings({"resource","unused"})
public class FileUtils {
  
  /**
   * 获取windows/linux的项目根目录
   * @return
   */
  public static String getConTextPath(){
    String fileUrl = Thread.currentThread().getContextClassLoader().getResource("").getPath();
    if("usr".equals(fileUrl.substring(1,4))){
      fileUrl = (fileUrl.substring(0,fileUrl.length()-16));//linux
    }else{
      fileUrl = (fileUrl.substring(1,fileUrl.length()-16));//windows
    }
    return fileUrl;
  }
    
  /**
   * 字符串转数组
   * @param str 字符串
   * @param splitStr 分隔符
   * @return
   */
  public static String[] StringToArray(String str,String splitStr){
    String[] arrayStr = null;
    if(!"".equals(str) && str != null){
      if(str.indexOf(splitStr)!=-1){
        arrayStr = str.split(splitStr);
      }else{
        arrayStr = new String[1];
        arrayStr[0] = str;
      }
    }
    return arrayStr;
  }
    
  /**
   * 读取文件
   *
   * @param Path
   * @return
   */
  public static String ReadFile(String Path) {
    BufferedReader reader = null;
    String laststr = "";
    try {
      FileInputStream fileInputStream = new FileInputStream(Path);
      InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
      reader = new BufferedReader(inputStreamReader);
      String tempString = null;
      while ((tempString = reader.readLine()) != null) {
        laststr += tempString;
      }
      reader.close();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return laststr;
  }
    
  /**
   * 获取文件夹下所有文件的名称 + 模糊查询(当不需要模糊查询时,queryStr传空或null即可)
   * 1.当路径不存在时,map返回retType值为1
   * 2.当路径为文件路径时,map返回retType值为2,文件名fileName值为文件名
   * 3.当路径下有文件夹时,map返回retType值为3,文件名列表fileNameList,文件夹名列表folderNameList
   * @param folderPath 路径
   * @param queryStr 模糊查询字符串
   * @return
   */
  public static HashMap<String, Object> getFilesName(String folderPath , String queryStr) {
    HashMap<String, Object> map = new HashMap<>();
    List<String> fileNameList = new ArrayList<>();//文件名列表
    List<String> folderNameList = new ArrayList<>();//文件夹名列表
    File f = new File(folderPath);
    if (!f.exists()) { //路径不存在
      map.put("retType", "1");
    }else{
      boolean flag = f.isDirectory();
      if(flag==false){ //路径为文件
        map.put("retType", "2");
        map.put("fileName", f.getName());
      }else{ //路径为文件夹
        map.put("retType", "3");
        File fa[] = f.listFiles();
        queryStr = queryStr==null ? "" : queryStr;//若queryStr传入为null,则替换为空(indexOf匹配值不能为null)
        for (int i = 0; i < fa.length; i++) {
          File fs = fa[i];
          if(fs.getName().indexOf(queryStr)!=-1){
             if (fs.isDirectory()) {
               folderNameList.add(fs.getName());
             } else {
               fileNameList.add(fs.getName());
             }
           }
        }
        map.put("fileNameList", fileNameList);
        map.put("folderNameList", folderNameList);
      }
    }
    return map;
  }
  
  /**
   * 以行为单位读取文件,读取到最后一行
   * @param filePath
   * @return
   */
  public static List<String> readFileContent(String filePath) {
    BufferedReader reader = null;
    List<String> listContent = new ArrayList<>();
    try {
      reader = new BufferedReader(new FileReader(filePath));
      String tempString = null;
      int line = 1;
      // 一次读入一行,直到读入null为文件结束
      while ((tempString = reader.readLine()) != null) {
        listContent.add(tempString);
        line++;
      }
      reader.close();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e1) {
        }
      }
    }
    return listContent;
  }
  
  /**
   * 读取指定行数据 ,注意:0为开始行
   * @param filePath
   * @param lineNumber
   * @return
   */
  public static String readLineContent(String filePath,int lineNumber){
    BufferedReader reader = null;
    String lineContent="";
    try {
      reader = new BufferedReader(new FileReader(filePath));
      int line=0;
      while(line<=lineNumber){
        lineContent=reader.readLine();
        line++;
      }
      reader.close();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e1) {
        }
      }
    }
    return lineContent;
  }
  
  /**
   * 读取从beginLine到endLine数据(包含beginLine和endLine),注意:0为开始行
   * @param filePath
   * @param beginLineNumber 开始行
   * @param endLineNumber 结束行
   * @return
   */
  public static List<String> readLinesContent(String filePath,int beginLineNumber,int endLineNumber){
    List<String> listContent = new ArrayList<>();
    try{
      int count = 0;
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
      String content = reader.readLine();
      while(content !=null){
        if(count >= beginLineNumber && count <=endLineNumber){
          listContent.add(content);
        
        content = reader.readLine();
        count++; 
      }
    } catch(Exception e){
    }
    return listContent;
  }
    
  /**
   * 读取若干文件中所有数据
   * @param listFilePath
   * @return
   */
  public static List<String> readFileContent_list(List<String> listFilePath) {
    List<String> listContent = new ArrayList<>();
    for(String filePath : listFilePath){
       File file = new File(filePath);
       BufferedReader reader = null;
      try {
        reader = new BufferedReader(new FileReader(file));
        String tempString = null;
        int line = 1;
        // 一次读入一行,直到读入null为文件结束
        while ((tempString = reader.readLine()) != null) {
          listContent.add(tempString);
          line++;
        }
        reader.close();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (reader != null) {
          try {
            reader.close();
          } catch (IOException e1) {
          }
        }
      }
    }
    return listContent;
  }
  
  /**
   * 文件数据写入(如果文件夹和文件不存在,则先创建,再写入)
   * @param filePath
   * @param content
   * @param flag true:如果文件存在且存在内容,则内容换行追加;false:如果文件存在且存在内容,则内容替换
   */
  public static String fileLinesWrite(String filePath,String content,boolean flag){
    String filedo = "write";
    FileWriter fw = null;
    try {
      File file=new File(filePath);
      //如果文件夹不存在,则创建文件夹
      if (!file.getParentFile().exists()){
        file.getParentFile().mkdirs();
      }
      if(!file.exists()){//如果文件不存在,则创建文件,写入第一行内容
        file.createNewFile();
        fw = new FileWriter(file);
        filedo = "create";
      }else{//如果文件存在,则追加或替换内容
        fw = new FileWriter(file, flag);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
      PrintWriter pw = new PrintWriter(fw);
      pw.println(content);
      pw.flush();
    try {
      fw.flush();
      pw.close();
      fw.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return filedo;
  }
      
  /**
   * 写文件
   * @param ins
   * @param out
   */
  public static void writeIntoOut(InputStream ins, OutputStream out) {
    byte[] bb = new byte[10 * 1024];
    try {
      int cnt = ins.read(bb);
      while (cnt > 0) {
        out.write(bb, 0, cnt);
        cnt = ins.read(bb);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        out.flush();
        ins.close();
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  
  /**
   * 判断list中元素是否完全相同(完全相同返回true,否则返回false)
   * @param list
   * @return
   */
  private static boolean hasSame(List<? extends Object> list){
    if(null == list)
      return false;
    return 1 == new HashSet<Object>(list).size();
  }
  
  /**
   * 判断list中是否有重复元素(无重复返回true,否则返回false)
   * @param list
   * @return
   */
  private static boolean hasSame2(List<? extends Object> list){
    if(null == list)
      return false;
    return list.size() == new HashSet<Object>(list).size();
  }
  
  /**
   * 增加/减少天数
   * @param date
   * @param num
   * @return
   */
  public static Date DateAddOrSub(Date date, int num) {
    Calendar startDT = Calendar.getInstance();
    startDT.setTime(date);
    startDT.add(Calendar.DAY_OF_MONTH, num);
    return startDT.getTime();
  }
  
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/hooly/p/8041328.html

延伸 · 阅读

精彩推荐