import java.io.*; import java.util.*; public class FileTest // useage: java FileTest a-token // a-token will be written to the end of oldfile.txt { public static void main(String[] args) throws FileNotFoundException { File oldFile = new File("oldfile.txt"); File newFile = new File("newfile.txt"); PrintStream ps = new PrintStream(newFile); // FileNotFoundException Scanner scanOld = null; System.out.println("Contents of oldfile.txt before -----------------------"); if (oldFile.exists()) { scanOld = new Scanner(oldFile); // FileNotfoundException while (scanOld.hasNext()) { String s = scanOld.nextLine(); // could combine these 2 lines ps.println(s); // except for next trace line System.out.println(s); // to trace } } if (args.length > 0) ps.println(args[0]); // use command line for text to add if (scanOld != null) // avoid null pointer exception first run scanOld.close(); // must close this connection -- before you can delete the old System.out.println("\n" + oldFile.delete()); // true if it worked // Can't rename over an existing file // System.out.println(oldFile.getName()); tried this to make sure File object is still in RAM // even though the disk file has been deleted ps.close(); // can't rename newFile without this disconnection System.out.println(newFile.renameTo(oldFile)); // true if it rename worked System.out.println("Contents of oldfile.txt after -----------------------"); scanOld = new Scanner(oldFile); // must rename to oldFile's name before this while (scanOld.hasNext()) // to trace System.out.println(scanOld.nextLine()); } }