Java文本输出常用类

原文链接: https://my.oschina.net/sshuj/blog/399124

package com.ss.extract;


import java.io.*;

import org.apache.log4j.Logger;


/**

 * 结果输出类

 * @author Shu

 */

public class ResultOutput {

private static Logger log = Logger.getLogger(ResultOutput.class);

/**

 * 将结果输出到txt文本文件中,其中的StaticValue.ABSTRACT_SAVE_PATH和StaticValue.FILE_NAME为输出

         * 地址

 * @param contents

 */

public void outputToTxt(String content){

File txt = creatTxtFile(StaticValue.ABSTRACT_SAVE_PATH,StaticValue.FILE_NAME);

FileOutputStream fileOutputStream = null;

BufferedOutputStream bufferedOutputStream = null;

OutputStreamWriter outputStreamWriter = null;

BufferedWriter out = null;

try {

fileOutputStream = new FileOutputStream(txt);

bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

outputStreamWriter = new OutputStreamWriter(bufferedOutputStream);

out = new BufferedWriter(outputStreamWriter);

out.write(content);

out.flush();

} catch (FileNotFoundException e) {

log.error("文件不存在!");

e.printStackTrace();

} catch (IOException e) {

log.error("文本摘要存储失败");

e.printStackTrace();

}finally{

if(out != null){

try {

out.close();

} catch (IOException e) {

log.error("BufferedWriter关闭失败!");

e.printStackTrace();

}

}

if(outputStreamWriter != null){

try {

outputStreamWriter.close();

} catch (IOException e) {

log.error("outputStreamWriter关闭失败!");

e.printStackTrace();

}

}

if(bufferedOutputStream != null){

try {

bufferedOutputStream.close();

} catch (IOException e) {

log.error("bufferedOutputStream关闭失败!");

e.printStackTrace();

}

}

if(fileOutputStream != null){

try {

fileOutputStream.close();

} catch (IOException e) {

log.error("fileOutputStream关闭失败!");

e.printStackTrace();

}

}

}

}

/**

 * 创建文件

 * @param path 文件存储路径

 * @param name 文件名字

 * @return File

 */

private File creatTxtFile(String path, String name){

File fileName = null;

fileName = new File(path + "\\" + name);

 if (!fileName.exists()) {

 try {

fileName.createNewFile();

} catch (IOException e) {

log.error("文件创建失败!");

e.printStackTrace();

}

 }

 return fileName;

}

}


转载于:https://my.oschina.net/sshuj/blog/399124

你可能感兴趣的:(Java文本输出常用类)