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

来源:互联网 发布:ubuntu启动anaconda 编辑:程序博客网 时间:2024/06/08 14:55
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+"/";}}

原创粉丝点击