ãjavaä¸ï¼å¯¹æ件è¿è¡è¿½å å
容æä½çä¸ç§æ¹æ³ï¼
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
//å¦ææ件åå¨ï¼å追å å
容ï¼å¦ææ件ä¸åå¨ï¼åå建æ件ï¼è¿½å å
容çä¸ç§æ¹æ³
public class AppendContentToFile {
@SuppressWarnings("static-access")
public static void main(String[] args) {
AppendContentToFile a = new AppendContentToFile();
a.method1();
a.method2("E:\\dd.txt", "222222222222222");
a.method3("E:\\dd.txt", "33333333333");
}
æ¹æ³1ï¼
public void method1() {
FileWriter fw = null;
try {
//å¦ææ件åå¨ï¼å追å å
容ï¼å¦ææ件ä¸åå¨ï¼åå建æ件
File f=new File("E:\\dd.txt");
fw = new FileWriter(f, true);
} catch (IOException e) {
e.printStackTrace();
}
PrintWriter pw = new PrintWriter(fw);
pw.println("追å å
容");
pw.flush();
try {
fw.flush();
pw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
æ¹æ³2ï¼
public static void method2(String file, String conent) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true)));
out.write(conent+"\r\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
æ¹æ³3ï¼
public static void method3(String fileName, String content) {
try {
// æå¼ä¸ä¸ªéæºè®¿é®æ件æµï¼æ读åæ¹å¼
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
// æ件é¿åº¦ï¼åèæ°
long fileLength = randomFile.length();
// å°åæ件æé移å°æ件尾ã
randomFile.seek(fileLength);
randomFile.writeBytes(content+"\r\n");
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}