diff options
Diffstat (limited to 'lib/nlp_ruby/fileutil.rb')
-rw-r--r-- | lib/nlp_ruby/fileutil.rb | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/lib/nlp_ruby/fileutil.rb b/lib/nlp_ruby/fileutil.rb new file mode 100644 index 0000000..825ceb4 --- /dev/null +++ b/lib/nlp_ruby/fileutil.rb @@ -0,0 +1,61 @@ +require 'zlib' + + +class ReadFile + + def initialize fn, encoding='utf-8' + if fn.split('.').last == 'gz' + @f = Zlib::GzipReader.new(File.new(fn, 'rb'), :external_encoding=>encoding) + elsif fn == '-' + @f = STDIN + STDIN.set_encoding encoding + else + @f = File.new fn, 'r' + @f.set_encoding encoding + end + end + + def gets + @f.gets { |line| yield line } + end + + def readlines + @f.readlines + end + + def readlines_strip + self.readlines.map{ |i| i.strip } + end + + def read + @f.read + end + + def close + @f.close if @f!=STDIN + end +end + +class WriteFile + + def initialize fn, encoding='utf-8' + if fn.split('.').last == 'gz' + @f = Zlib::GzipWrite.new(File.new(fn, 'wb+'), :external_encoding=>encoding) + elsif fn == '-' + @f = STDOUT + STDOUT.set_encoding encoding + else + @f = File.new fn, 'w+' + @f.set_encoding encoding + end + end + + def write s + @f.write s + end + + def close + @f.close if @f!=STDIN + end +end + |