最近更新: 2007-04-12

字元編碼轉換、基本檔案讀取與建立壓縮檔

Ruby 練習程式。讀取UTF-8編碼文字檔,轉換成Big5編碼後顯示。開啟檔案後分別以 Loop 式的 gets, Iterator 的 each, 以及一次讀入陣列的 readlines 三種形式操作。再以封絕(Closure)方式完成開啟、讀取及轉碼輸出。最後嘗試以 popen 進行管線(pipe)操作,呼叫壓縮工具將轉碼後的資料壓縮儲存。

require 'iconv'

conv = Iconv.new('big5', 'utf-8')
fh = File.open('test.txt', 'r')

print "Loop way...\n"
while line = fh.gets
    print conv.iconv(line)
end
print "-----------\n";

fh.rewind

print "Iterate way...\n"
fh.each do |line|
    print conv.iconv(line)
end
print "-----------\n";

fh.rewind

print "Read to array\n"
dataSet = fh.readlines
dataSet.each { |line|
    print conv.iconv(line)
}
print "-----------\n";

fh.close
conv.close

print "Block way...\n"
File.open('test.txt') { |fh|
    Iconv.open('big5', 'utf-8') { |conv|
        fh.each { |line|
            print conv.iconv(line)
        }
    }
}
print "-----------\n";

compressor = 'C:/progra~1/7-zip/7z.exe'
compressCommand = compressor + ' a -sitest_big5.txt test.7z'
IO.popen(compressCommand, 'w') { |zfh|
    File.open('test.txt') { |fh|
        Iconv.open('big5', 'utf-8') { |conv|
            fh.each { |line|
                zfh.print conv.iconv(line)
            }
        }
    }
}
樂多舊網址: http://blog.roodo.com/rocksaying/archives/2995543.html

樂多舊回應
lxuzytacs@mail.com(ncrsqoebl yruovati) (#comment-10394413)
Sun, 13 May 2007 09:25:04 +0800
wdcfspm yflw orntup uaglnve zarq tvrulizcy hvgd