- Import <a href="HTTP://LIB.CSDN.NET/BASE/17" class=' Replace_word ' title="Java ee Knowledge Base" target=' _blank ' style=' color: #df3434; font-weight:bold; ' >java</a>.io. BufferedWriter;
- Import Java.io.File;
- Import Java.io.FileOutputStream;
- Import Java.io.FileWriter;
- Import java.io.IOException;
- Import Java.io.OutputStreamWriter;
- Import Java.io.RandomAccessFile;
- /**
- *
- * @author Malik
- * @version 2011-3-10 10:49:41
- */
- Public class AppendFile {
- public static void method1 (string file, String conent) {
- BufferedWriter out = null;
- try {
- out = new BufferedWriter (Newoutputstreamwriter (new FileOutputStream (file, true));
- Out.write (conent);
- } catch (Exception e) {
- E.printstacktrace ();
- } finally {
- try {
- if (out! = null) {
- Out.close ();
- }
- } catch (IOException e) {
- E.printstacktrace ();
- }
- }
- }
- /**
- * Append file: Use FileWriter
- *
- * @param fileName
- * @param content
- */
- public static void Method2 (String fileName, string content) {
- FileWriter writer = null;
- try {
- //Open a write file, the second parameter in the constructor true indicates that the file is written in append form
- writer = New FileWriter (FileName, true);
- Writer.write (content);
- } catch (IOException e) {
- E.printstacktrace ();
- } finally {
- try {
- if (writer! = null) {
- Writer.close ();
- }
- } catch (IOException e) {
- E.printstacktrace ();
- }
- }
- }
- /**
- * Append file: Use Randomaccessfile
- *
- * @param filename
- * @param content Additions
- */
- public static void Method3 (String fileName, string content) {
- Randomaccessfile randomfile = null;
- try {
- //Open a random Access file stream, read and write
- Randomfile = New Randomaccessfile (FileName, "RW");
- //File length, number of bytes
- Long filelength = Randomfile.length ();
- //Move the Write file pointer to the end of the file.
- Randomfile.seek (filelength);
- Randomfile.writebytes (content);
- } catch (IOException e) {
- E.printstacktrace ();
- } finally{
- if (randomfile! = null) {
- try {
- Randomfile.close ();
- } catch (IOException e) {
- E.printstacktrace ();
- }
- }
- }
- }
- public static void Main (string[] args) {
- try{
- File File = new file ("D://text.txt");
- if (File.createnewfile ()) {
- System.out.println ("Create file successed");
- }
- Method1 ("D://text.txt", "123");
- METHOD2 ("D://text.txt", "123");
- Method3 ("D://text.txt", "123");
- }catch (Exception e) {
- System.out.println (e);
- }
- }
- }
Three ways to append file content to Java