Java 示例 - 将字符串附加到文件
-
问题描述
如何在现有文件中附加字符串? -
解决方案
此示例显示如何使用 filewriter 方法在现有文件中附加字符串。import java.io.*; public class Main { public static void main(String[] args) throws Exception { try { BufferedWriter out = new BufferedWriter(new FileWriter("filename")); out.write("aString1\n"); out.close(); out = new BufferedWriter(new FileWriter("filename",true)); out.write("aString2"); out.close(); BufferedReader in = new BufferedReader(new FileReader("filename")); String str; while ((str = in.readLine()) != null) { System.out.println(str); } } in.close(); catch (IOException e) { System.out.println("exception occoured"+ e); } } }
-
结果
上面的代码示例将产生以下结果。aString1 aString2
下面是在java中在现有文件中追加字符串的例子import java.io.File; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; public class AppendToFileExample { public static void main( String[] args ) { try { String data = " CAINIAOYA is a best website in the world"; File f1 = new File("C:\\Users\\TutorialsPoint7\\Desktop\\abc.txt"); if(!f1.exists()) { f1.createNewFile(); } FileWriter fileWritter = new FileWriter(f1.getName(),true); BufferedWriter bw = new BufferedWriter(fileWritter); bw.write(data); bw.close(); System.out.println("Done"); } catch(IOException e){ e.printStackTrace(); } } }
上面的代码示例将产生以下结果。Done