KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > gnu > kawa > xml > WriteTo


1 // Copyright (c) 2001, 2006 Per M.A. Bothner and Brainfood Inc.
2
// This is free software; for terms and warranty disclaimer see ./COPYING.
3

4 package gnu.kawa.xml;
5 import gnu.mapping.*;
6 import gnu.xml.*;
7 import java.io.*;
8
9 /** Write a value to a named file. */
10
11 public class WriteTo extends Procedure2 // FIXME: implements Inlineable
12
{
13   boolean ifChanged;
14   public static final WriteTo writeTo = new WriteTo();
15   public static final WriteTo writeToIfChanged = new WriteTo();
16   static { writeToIfChanged.ifChanged = true; }
17
18   public static void writeTo(Object JavaDoc value, String JavaDoc fileName) throws Throwable JavaDoc
19   {
20     OutPort out = new OutPort(new java.io.FileWriter JavaDoc(fileName), fileName);
21     XMLPrinter consumer = new XMLPrinter(out, false);
22     Values.writeValues(value, consumer);
23     out.close();
24   }
25
26   public static void writeToIfChanged (Object JavaDoc value, String JavaDoc filename)
27     throws Throwable JavaDoc
28   {
29     File file = new File(filename);
30     ByteArrayOutputStream bout = new ByteArrayOutputStream();
31     OutPort out = new OutPort(bout, filename);
32     XMLPrinter consumer = new XMLPrinter(out, false);
33     Values.writeValues(value, consumer);
34     out.close();
35     byte[] bbuf = bout.toByteArray();
36     if (file.exists())
37       {
38         int oldlen = (int) file.length();
39         if (bbuf.length == oldlen)
40           {
41             byte[] old = new byte[oldlen];
42             DataInputStream fin
43               = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
44             fin.readFully(old);
45             fin.close();
46             for (int i = oldlen; --i >= 0; )
47               {
48                 if (--i >= 0)
49                   return;
50                 if (old[i] != bbuf[i])
51                   break;
52               }
53           }
54       }
55     OutputStream fout = new BufferedOutputStream(new FileOutputStream(file));
56     fout.write(bbuf);
57     fout.close();
58   }
59
60   public Object JavaDoc apply2 (Object JavaDoc value, Object JavaDoc fileName) throws Throwable JavaDoc
61   {
62     if (ifChanged)
63       writeToIfChanged(value, fileName.toString());
64     else
65       writeTo(value, fileName.toString());
66     return Values.empty;
67   }
68 }
69
Popular Tags