2012-05-09 62 views
0

我正在Scala中创建一个简单的Web服务器,我试图将事件日志记录实现到一个XML文件。 XML结构是这样的:Scala - 将XML追加到文件

<log> 
     <event> 
      <type>Info/Warning/Error/etc</type> 
      <description>File not found etc</description> 
      <file>/etc/etc.etc</file> 
      <ip>1.2.3.4</ip> 
      <time>12:34:56 1st Jan 2012</time> 
     </event> 
     <event> 
      etc... 
     <event> 
</log> 

目前即时通讯试图将XML写这样的文件:

var logEvent = 
    <log> 
<event> 
<type>ERROR</type> 
<description>The Requested File was not found</description> 
<file>{path}</file> 
<ip>{connection.getRemoteSocketAddress}</ip> 
<time>{new Date(System.currentTimeMillis)}</time> 
</event> 
</log> 

XML.save(logFile, logEvent, "UTF-8", true, null) 

然而,当我检查文件只有最近甚至有和刷新文件当服务器正在运行时,会显示每个事件替换文件中的最后一个事件。

我也尝试使用FileOutputStream,附加功能与XML.write一起启用,但是在每个事件之前插入XML模式,这会阻止它被识别为正确的XML文件。它还在每个事件周围添加根<log>标签。

我能想到的唯一方法是在文件中加载当前的XML,添加到文件中,然后写回来,这对我来说似乎效率低下。

是否有一种简单的方法将XML追加到我缺少的文件中? 任何帮助表示赞赏:)

回答

0

如果以该格式追加另一个日志,那么您的文档将是无效 XML,因为缺少顶级容器。
如果你不在乎,你可以简单地使用java.nio.channels.FileChannel。

import java.nio._ 
import java.io._ 

def appendToFile(f: File) { 
    var foutstream: Option[FileOutputStream] = None 
    lazy val foutchannel = foutstream.get.getChannel 
    try { 
    foutstream = Some(new FileOutputStream(f, true) 
    val buffer = ByteBuffer.allocate(1024) 
    "this text will be appended" foreach (buffer.put(_.toByte)) 
    buffer.flip 
    foutchannel.write(buffer) 
    foutchannel.close 
    foutstream.get.close 
    } catch { 
    case e: Exception => e printStackTrace 
    } 
}