欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

创建文本并写入内容,创建文本写入内容,前段时间巡检项目需要采集

来源: javaer 分享于  点击 30308 次 点评:126

创建文本并写入内容,创建文本写入内容,前段时间巡检项目需要采集


前段时间巡检项目需要采集日志,无奈巡检项目太多了.上网查了点资料,就写了这个类.主要功能是实现:拿到日志后,然后在指定路径下生成txt文件并把日志写到里面。

package util.io;import java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;import java.io.IOException;import com.regaltec.commons.exception.ApplicationException;public class CreateFileUtil {    private static final CreateFileUtil instance = new CreateFileUtil();    /**     * 单例构造     *      * @return     */    public static CreateFileUtil getInstance() {        return instance;    }    /**     * 创建文件     *      * @param str     * @param fileName     * @param absoluteFilePath     * @return     * @throws ApplicationException     */    public boolean createFile(String fileName, String absoluteFilePath)            throws ApplicationException {        if (absoluteFilePath == null || absoluteFilePath.length() == 0) {            throw new ApplicationException("创建文件的绝对路径为空");        }        if (fileName == null || fileName.length() == 0) {            throw new ApplicationException("文件名为空");        }        File file = new File(absoluteFilePath + File.separator + fileName);        try {            if (!file.exists()) {                file.createNewFile();                return true;            }        } catch (Exception e) {            // TODO: handle exception            e.printStackTrace();        }        return false;    }    /**     * 往文件写入内容     *      * @param str     * @param filePath     * @throws ApplicationException     */    public void writeTXTtoFile(String str, String filePath)            throws ApplicationException {        if (str == null || str.length() == 0) {            throw new ApplicationException("需要写入的内容为空");        }        if (filePath == null || filePath.length() == 0) {            throw new ApplicationException("文件路径为空");        }        File file = new File(filePath);        if (!file.exists()) {            try {                file.createNewFile();                // 写入内容                BufferedWriter output = new BufferedWriter(new FileWriter(file));                output.write(str);                output.close();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }    }    public String getAbsoluteFilePath(Object obj) {        String filePath = "C://Users//lenovo//Desktop//新建文件夹";        filePath += File.separator + obj.getClass().getSimpleName() + "Log.txt";        return filePath;    }}//该片段来自于http://byrx.net
相关栏目:

用户点评