Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
ネバーバード日記
[go: Go Back, main page]

Hatena::Diarytri はてなブックマーク はてなフォトライフ
    
はてな
 ようこそゲストさん  最新の日記 ユーザー登録 ログイン ヘルプ

ネバーバード日記

2004-04-28

[] eachLineを使ってソースに行番号をつける

File.eachLine(Closure)を使います。ストリームのcloseをする必要がないので楽チン。

#!/usr/bin/env groovy

import java.io.File;

file = new File("/tmp/Miki.java");
buf = new StringBuffer();
i=1;

file.eachLine {line| 
  buf.append("${i++}:${line}\n");
}

println("<pre>${buf}</pre>");

[][] 行番号付きソース表示プラグイン

JSPWikiのプラグイン内でfile.eachLineを使うとなぜかJasperExceptionになってしまいます*1。とりあえず、使わないように書き直したのですがGroovyらしくなくなってしまいました(涙)。

#!/usr/bin/env groovy

import com.ecyrd.jspwiki.plugin.WikiPlugin;
import com.ecyrd.jspwiki.WikiContext;
import java.util.Map;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;

class Miki implements WikiPlugin {

    public String execute(WikiContext context, Map params ) 
      throws PluginException {

      servletContext = context.getEngine().getServletContext();
      
      src = params.get("src");
      fileName = servletContext.getRealPath(src);
      file = new File(fileName);
  
      buf = new StringBuffer("<pre>");
      i=1;
     
      br = new BufferedReader(new FileReader(file));
      try {
        line = br.readLine();
        while (line != null) {
          buf.append(i++);
          buf.append(":");
          buf.append(line);
          buf.append('\n');
          line = br.readLine();
        }
      }
      finally {
        br.close();
      }
      buf.append("<pre>");
      return buf.toString();
    }
}

*1:JBoss 3.2.3にJSPWiki.warをディレクトリに展開してインストールしています

トラックバック - http://d.hatena.ne.jp/neverbird/20040428