Java按行讀寫文件

public class FileUtil {
	// 判斷指定文件是否存在,若isCreate=true則文件不存在時創建
	public static boolean exist(String filename, boolean isCreate) throws IOException {
		File file = new File(filename);
		boolean exist = file.exists();
		if(exist) return true; // 文件存在返回true
		if(isCreate) return file.createNewFile(); // 文件不存在且需要創建時返回是否創建成功
		return false; // 文件不存在且不需要創建時返回false
	}
	
	// 寫入文件,append=true爲追加方式寫入
	public static void writeFile(String fileName,String str, boolean append) throws IOException{                
            FileWriter fw = new FileWriter(fileName, append);
            fw.write(str);
            fw.flush();
            fw.close();
        } 
	
	// 按行寫入文件,append=true爲追加方式寫入
	public static void writeFileByLines(String fileName,String []strs, boolean append) throws IOException{                
            FileWriter fw = new FileWriter(fileName, append);
            for (String str: strs){
                fw.write(str);
                fw.write("\n");
            }        
            fw.flush();
            fw.close();
        } 
	
	// 按行讀取文件
    public static List<String> readFileByLines(String fileName) throws IOException{
        File file = new File(fileName);
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String tempString = null;
        List<String> strs = new ArrayList<String>();
        while ((tempString = reader.readLine()) != null){
            strs.add(tempString);
        }
        reader.close();
        return strs;
    }  
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章