首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

把内容写下指定目录指定文件的java文件工具类,支持日期格式目录名的生成

2013-09-05 
把内容写入指定目录指定文件的java文件工具类,支持日期格式目录名的生成package com.yanek.testimport ja

把内容写入指定目录指定文件的java文件工具类,支持日期格式目录名的生成

package com.yanek.test;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.UnsupportedEncodingException;import java.text.SimpleDateFormat;public class FileUtil {private static SimpleDateFormat sdfYmd = new SimpleDateFormat("yyyy-MM-dd");/** * @param args *  */public static void main(String[] args) {writeContentToLocalFile("/temp/test/","test1.txt","test\r\n","UTF-8");writeContentToLocalFile("/temp/test/","test1.txt","test\r\n","UTF-8");String currentDate = sdfYmd.format(System.currentTimeMillis());String basePath="/temp";String fullpath=basePath+getDirname(currentDate);writeContentToLocalFile(fullpath,"test1.txt","test111\r\n","UTF-8");}/** *  * @param dirname  目录名 * @param localfilename 文件名 * @param content 文件内容 * @param charset 编码 */public static void writeContentToLocalFile(String dirname,String localfilename,String content,String charset){File f=new File(dirname);if (!f.exists()){f.mkdirs();}String localFilename = dirname+File.separator+localfilename;FileOutputStream fos;try {fos = new FileOutputStream(localFilename,true);try {OutputStreamWriter writer = new OutputStreamWriter(fos, charset);try {writer.write(content);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {writer.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {fos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} //覆盖原来的文件 追加到后面}/** * 根据日期字符串得到目录名 格式: /2008/10/15/ * @param datatime * @return */public static String getDirname(String datatime){String nian=datatime.substring(0,4);String yue=datatime.substring(5,7);String ri=datatime.substring(8,10);        return "/"+nian+"/"+yue+"/"+ri+"/";}}

热点排行