java文件讀寫工具類分享
更新時間:2018年02月01日 10:56:17 作者:漂流的老妖怪
這篇文章主要為大家詳細(xì)介紹了java文件讀寫工具類,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了java文件讀寫工具類的具體代碼,供大家參考,具體內(nèi)容如下
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; } /** * 字符串轉(zhuǎn)數(shù)組 * @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; } /** * 獲取文件夾下所有文件的名稱 + 模糊查詢(當(dāng)不需要模糊查詢時,queryStr傳空或null即可) * 1.當(dāng)路徑不存在時,map返回retType值為1 * 2.當(dāng)路徑為文件路徑時,map返回retType值為2,文件名fileName值為文件名 * 3.當(dāng)路徑下有文件夾時,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為文件結(jié)束 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; } /** * 讀取指定行數(shù)據(jù) ,注意: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數(shù)據(jù)(包含beginLine和endLine),注意:0為開始行 * @param filePath * @param beginLineNumber 開始行 * @param endLineNumber 結(jié)束行 * @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; } /** * 讀取若干文件中所有數(shù)據(jù) * @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為文件結(jié)束 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; } /** * 文件數(shù)據(jù)寫入(如果文件夾和文件不存在,則先創(chuàng)建,再寫入) * @param filePath * @param content * @param flag true:如果文件存在且存在內(nèi)容,則內(nèi)容換行追加;false:如果文件存在且存在內(nèi)容,則內(nèi)容替換 */ public static String fileLinesWrite(String filePath,String content,boolean flag){ String filedo = "write"; FileWriter fw = null; try { File file=new File(filePath); //如果文件夾不存在,則創(chuàng)建文件夾 if (!file.getParentFile().exists()){ file.getParentFile().mkdirs(); } if(!file.exists()){//如果文件不存在,則創(chuàng)建文件,寫入第一行內(nèi)容 file.createNewFile(); fw = new FileWriter(file); filedo = "create"; }else{//如果文件存在,則追加或替換內(nèi)容 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(); } } } /** * 判斷l(xiāng)ist中元素是否完全相同(完全相同返回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(); } /** * 判斷l(xiāng)ist中是否有重復(fù)元素(無重復(fù)返回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(); } /** * 增加/減少天數(shù) * @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(); } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
零基礎(chǔ)學(xué)Java:Java開發(fā)工具 Eclipse 安裝過程創(chuàng)建第一個Java項目及Eclipse的一些基礎(chǔ)使用技巧
這篇文章主要介紹了零基礎(chǔ)學(xué)Java:Java開發(fā)工具 Eclipse 安裝過程創(chuàng)建第一個Java項目及Eclipse的一些基礎(chǔ)使用技巧,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09springboot升級到j(luò)dk21最新教程(2023年)
你還在使用jdk8?快來看看最新出爐的SpringBoot+jdk21如何使用,下面這篇文章主要給大家介紹了關(guān)于springboot升級到j(luò)dk21的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-10-10盤點總結(jié)SpringBoot自帶工具類使用提升開發(fā)效率
這篇文章主要為大家介紹了盤點總結(jié)SpringBoot自帶工具類使用提升開發(fā)效率,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12詳解Java去除json數(shù)據(jù)中的null空值問題
這篇文章主要介紹了詳解Java去除json數(shù)據(jù)中的null空值問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08