Created
October 18, 2010 09:59
-
-
Save kimukou/631991 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.nio.* | |
import java.nio.charset.* | |
import java.nio.channels.* | |
def decodeStr={fis,encoding -> | |
Charset cs = Charset.forName(encoding) | |
FileChannel ch = fis.getChannel() | |
CharsetDecoder decoder = cs.newDecoder() | |
boolean end = false //ファイルの終わりまで読み込んだかどうか | |
// バッファーを用意する。 | |
ByteBuffer bb = ByteBuffer.allocateDirect(256) // bbは書き込める状態 | |
CharBuffer cb = CharBuffer.allocate(256) // cbは書き込める状態 | |
StringBuilder sb = new StringBuilder() | |
while (!end){ | |
int len = ch.read(bb) // bbへ書き込み | |
if (len < 0) { | |
end = true | |
} | |
bb.flip() // bbを読み込み状態に変更 | |
CoderResult cr = decoder.decode(bb, cb, end) // bbから読み込み、cbへ書き込む | |
if (!cr.isUnderflow()) { | |
cr.throwException() | |
} | |
if (end) { | |
cr = decoder.flush(cb) // cbへ書き込む | |
if (!cr.isUnderflow()) { | |
cr.throwException() | |
} | |
} | |
cb.flip() // cbを読み込み状態に変更 | |
String str = cb.toString() | |
//println str | |
sb.append str | |
bb.compact() // データを詰めて書き込める状態に変更 | |
cb.clear() // cbを書き込み状態に変更 | |
} | |
fis.close() // 取得したチャネルもクローズされる | |
return sb.toString() | |
} | |
String encoding = "UTF-8" | |
filename="D:/test1.txt" | |
//filename=args[0] | |
InputStream st = new FileInputStream(filename) | |
retstr = decodeStr(st, encoding) | |
println "retstr=\n${retstr}" | |
//println getClass().getResourceAsStream(".").toURL() | |
//st=new //FileInputStream(getClass().classLoader.getResourceAsStream("test1.txt").toURI().getPath()) | |
//st=getClass().getResourceAsStream("test1.txt") | |
//println "st=${st}" | |
//println getClass().classLoader.dump() | |
//st=getClass().classLoader.getResourceAsStream('test1.txt') | |
//println "st=${st}" | |
//retstr = decodeStr(st, encoding) | |
//println "retstr=\n${retstr}" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment