Java檔案操作Utils
阿新 • • 發佈:2019-02-07
Java檔案操作常用函式記錄:
package com.springwoods.utills; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; public class FileUtils { public FileUtils(){ System.out.println("----->"); } public static boolean IsExist(String path){ boolean Is; File file=new File(path); Is = file.exists(); return Is; } /** * @方法名稱 :wrieteFile * @功能描述 :寫檔案操作 * @返回值型別 :void * @param path 檔案路徑 ,content 寫的內容 */ public static void wrieteFile(String path, String content){ if(IsExist(path)) { OutputStream out; try { out = new BufferedOutputStream(new FileOutputStream(path)); byte[] time = content.getBytes(); out.write(time); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } /** * @方法名稱 :readLineFile * @功能描述 :一行一行讀檔案內容 * @返回值型別 :void * @param filename 檔名 */ public static void readLineFile(String filename){ try { FileInputStream in = new FileInputStream(filename); InputStreamReader inReader = new InputStreamReader(in, "UTF-8"); BufferedReader bufReader = new BufferedReader(inReader); String line = null; int i = 1; while((line = bufReader.readLine()) != null){ System.out.println("第" + i + "行:" + line); i++; } bufReader.close(); inReader.close(); in.close(); } catch (Exception e) { e.printStackTrace(); System.out.println("讀取" + filename + "出錯!"); } } /** * @方法名稱 :writeLineFile * @功能描述 :一行一行寫檔案 * @返回值型別 :void * @param filename 檔名,content 寫的內容 */ public static void writeLineFile(String filename, String[] content){ if(IsExist(filename)) { try { FileOutputStream out = new FileOutputStream(filename); OutputStreamWriter outWriter = new OutputStreamWriter(out, "UTF-8"); BufferedWriter bufWrite = new BufferedWriter(outWriter); for (int i = 0; i < content.length; i++) { bufWrite.write(content[i] + "\r\n"); } bufWrite.close(); outWriter.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.out.println("讀取" + filename + "出錯!"); } } } /** * @方法名稱 :writeLineFile * @功能描述 :一行一行寫檔案 * @返回值型別 :void * @param filename 檔名,content 寫的內容 */ public static void writeLineFile(String filename, String content){ try { FileOutputStream out = new FileOutputStream(filename, true); OutputStreamWriter outWriter = new OutputStreamWriter(out, "UTF-8"); BufferedWriter bufWrite = new BufferedWriter(outWriter); bufWrite.write(content + "\r\n"); bufWrite.close(); outWriter.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.out.println("讀取" + filename + "出錯!"); } } }