summaryrefslogtreecommitdiff
path: root/lib/nlp_ruby/fileutil.rb
blob: 825ceb4ccf249c3cb7d47113676b7aad4dbb932b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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