/* Written by Jen Chen Updated on 01/7/05 */ import java.util.*; import java.util.zip.*; import java.io.*; public class IO_AppendToFile { public static void main(String[] args) throws IOException{ String file = "URL.htm"; String dir = "C:\\jen\\Temp\\FileIO_1"; File inFile = new File(file); File myDir = new File(dir); BufferedReader fbuf = null; int linenum = 0; String line; File output = new File(dir,"output.txt"); output.createNewFile(); //create a new file if necessary. BufferedWriter out = new BufferedWriter(new FileWriter(output)); try{ fbuf = new BufferedReader(new FileReader(file)); line = fbuf.readLine(); while(line != null){ linenum++; out.write(line + "\n"); line = fbuf.readLine(); } } catch(Exception e) { System.out.println(e); } if(fbuf != null) try{ fbuf.close(); } catch(Exception e){} out.close(); //Now we append to the end of the file output.txt by specifying the 2nd parameter of the //FileWriter() constructor to be "true". //We will append File fileout = new File(dir,"output.txt"); fileout.createNewFile(); BufferedWriter out2 = new BufferedWriter(new FileWriter(fileout.getPath(), true)); out2.write("Get the absolute path of the given file, then append this path to the end " + "of the file output.txt\n"); out2.write(fileout.getAbsolutePath() + "\n"); out2.write("Get the directory's name of this file then append this path to the end of the file output.txt" + "\n"); out2.write(fileout.getParent() + "\n"); out2.write("Listing the contents of the current directory, then append the results to " + "the file output.txt\n"); String st[] = myDir.list(); for(int i = 0; i < st.length; i++) out2.write("\t" + st[i] + "\n"); out2.write("Listing the contents of the current directory, then filtering out all files except those end " + "with the .java suffix, then append the results to " + "the file output.txt\n"); FilenameFilter filter = new FilenameFilter() { public boolean accept(File myDir, String name) { return name.endsWith(".java"); } }; String st2[] = myDir.list(filter); for(int i = 0; i < st2.length; i++) out2.write("\t" + st2[i] + "\n"); out2.close(); //fileout.deleteOnExit(); }//end of main() }//end of class IO_1{}