Java如何在文件末尾追加内容呢?
下文笔者讲述使用java代码在文件末尾添加内容的方法分享,如下所示
文件追加内容的实现思路
借助 FileOutputStream 对象追加内容 使用 FileWriter对象追加内容例:文件追加内容的示例
import java.io.*; public class AddContent2TxtLast { /** * "\\r\\n"用于换行 * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // 可以是其它格式的文件 String pathName = "D:\\test\java265.txt"; String conent = "\r\n测试,把字符追加到文件末尾"; addContentPlus(pathName, conent); conent = "\r\naddContent2TxtLast"; addContent2TxtLast(pathName, conent); conent = "\r\nmethod2"; method2(pathName, conent); } /** * 追加文件内容:<p> * 判断文件是否存在,不存在则创建<p> * 使用FileOutputStream,在构造FileOutputStream时,把第二个参数设为true<p> * * @param pathName * @param conent */ public static void addContentPlus(String pathName, String conent) throws IOException { File file = new File(pathName); // 判断文件不存在,返回 if (!judeFileExists(file)) { return; } if (!file.exists()) { file.createNewFile(); } BufferedWriter out = null; try { out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(file, true))); out.write(conent); } catch (Exception e) { e.printStackTrace(); } finally { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 追加文件:使用FileOutputStream,在构造FileOutputStream时 * 把第二个参数设为true,表示在文件末尾追加 * * @param pathName * @param conent * @throws IOException */ public static void addContent2TxtLast(String pathName, String conent) throws IOException { FileOutputStream fos = new FileOutputStream(pathName, true); fos.write(conent.getBytes()); fos.flush(); fos.close();//流要及时关闭 } /** * 追加文件:使用FileWriter * * @param pathName * @param content */ public static void method2(String pathName, String content) throws IOException { FileWriter writer = null; try { // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件 writer = new FileWriter(pathName, true); writer.write(content); } catch (IOException e) { e.printStackTrace(); } finally { writer.flush(); writer.close(); } } // 判断文件是否存在 public static boolean judeFileExists(File file) { if (file.exists()) { System.out.println("File exists"); return Boolean.TRUE; } else { System.out.println("File not exists, please create it ..."); return Boolean.FALSE; } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。