@Service @Transactional public class FileOperatorImpl implements FileOperator { private static final Log log = LogFactory.getLog(FileOperatorImpl.class); public static int BF_SIZE = 2048;
public String readFile(String path) { try { BufferedReader reader = new BufferedReader(new FileReader(path)); try { StringBuilder builder = new StringBuilder(); char[] ch = new char[BF_SIZE]; for (int i = 0; (i = reader.read(ch)) != -1;) { builder.append(ch, 0, i); } return builder.toString(); } finally { reader.close(); } } catch (FileNotFoundException e) { log.warn("文件未找到!:" + path, e); } catch (IOException e) { log.warn("IO异常!:" + path, e); } return ""; }
public void writeFile(String path, String name, String content) { if (content == null) { content = ""; } try { File f = new File(path); if (!f.exists()) { f.mkdirs(); } BufferedWriter writer = new BufferedWriter(new FileWriter(path + name)); try { writer.write(content); } finally { writer.close(); } } catch (IOException e) { throw new RuntimeException(e); } }