在java编程中,如何向现有文件中附加(写入)一个字符串?
此示例显示如何使用filewriter()
方法在现有文件中附加字符串。
package com.yiibai;
import java.io.*;
public class AppendString2File {
public static void main(String[] args) throws Exception {
String filename = "write-filename.txt";
try {
BufferedWriter out = new BufferedWriter(new FileWriter(filename));
out.write("This is the first String1\n");
out.close();
out = new BufferedWriter(new FileWriter(filename, true));
out.write("This is the second String2\n");
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);
}
}
}
执行上述示例代码,将产生以下结果 -
This is the first String1
This is the second String2
示例-2
以下是在java中向文件中附加(写入)字符串的另一个示例。
package com.yiibai;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class AppendString2File2 {
public static void main( String[] args ) {
try {
String data = " yiibai.com is one of the best website in the world";
File f1 = new File("F:/worksp/javaexamples/java_files/write-filename2.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