Package File;import Java.io.file;import Java.io.filenotfoundexception;import java.io.filewriter;import Java.io.writer;import java.util.scanner;/** * * @author Administrator * */public class Fileutil {public static void M Ain (String args[]) {string srcfile = "D:/old.txt"; String tofile = "D:/new.txt"; try {String result = read (srcfile); Write (result, tofile); } catch (Exception e) {e.printstacktrace (); }} private static String read (String srcfile) throws FileNotFoundException {Scanner in = new Scanner (new File (srcfile)); String result = ""; while (In.hasnextline ()) {result + = In.nextline () + "\ r \ n"; } in.close (); return result; } private static void write (string result, String tofile) throws Exception {Writer w = new FileWriter (New File (ToFile)); W.write (result); W.flush (); W.close (); }}
Append file
Package File;import Java.io.file;import Java.io.filewriter;import java.io.ioexception;import Java.io.randomaccessfile;import java.io.writer;/** * Two methods * Append file * @author Administrator * */public class AppendFile {Publ IC static void Append1 () throws ioexception{string content= "---the first method to add the contents of the file-------\r\n6666"; Writer w = new FileWriter (New File ("New.txt"), true); w.append (content); System.out.println ("added success"); String c1= "1q1q\r\n"; W.append (C1); W.flush (); W.close ();} public static void Append2 () throws Ioexception{randomaccessfile Randomfile = new Randomaccessfile (New File ("D://new.txt ")," RW "); File length, number of bytes long filelength = Randomfile.length (); Moves the write file pointer to the end of the file. Randomfile.seek (filelength); Randomfile.writebytes ("00000xxxxxxxx11111"); Randomfile.close (); } public static void Main (string[] args) throws IOException {Append1 (); Append2 ();}}
Java read-write file