Something more useful,
October 22, 2008 at 9:47 PM
I prefer to have a file that I can write to like a log file such as appending or prepending text to the file. Here is an example that may be useful to someone.
public static void write(String content, char type) { try { String outfile = "logs/out.txt"; System.out.println("Writing to file: "+outfile); if(type == 'a' || type == 'p') { // needs input from the file first String in = File.read(outfile); if(type == 'a') { System.out.println(" Prepending Content: "+content); content = in+content; } else if (type == 'p') { // prepend System.out.println(" Prepending Content: "+content); content = content+in; } } // Create file BufferedWriter out = new BufferedWriter(new FileWriter(outfile)); System.out.println("Writing Content: "+content); // if !append or prepend then the file is overwritten. otherwise it contains the text in front of it or behind it for what was added. out.write(content); // Close the output stream out.close(); } catch (Exception e) { // Catch exception if any System.err.println("Error: "+e.getMessage()); System.exit(-1); } }
public static String read(String infile) { try { String content = new String(); BufferedReader in = new BufferedReader(new FileReader(infile)); String read = in.readLine(); while(read != null) { if(read.length()>0 && read.charAt(read.length()-1) != '\n') { read += "\n"; } content += read; read = in.readLine(); } in.close(); System.out.println("Read Content: "+content); return content; } catch (Exception e) { // Catch exception if any System.err.println("Error: "+e.getMessage()); System.exit(-1); } return new String(); } }