4. 英文字串壓縮程式

讀取 JSON 的方式類似於 Gson

# 取得當前執行路徑 AppDomain.CurrentDomain.BaseDirectory

using System.Text.Json.Nodes;

var json = JsonObject.Parse(File.OpenText("C:\\Users\\TangJin\\source\\repos\\Q4\\Q4\\huffman.json").ReadToEnd()).AsObject();

Console.Write("請輸入內文為英文的檔名(.txt): ");
var file = Console.ReadLine();
var data = File.OpenText(AppDomain.CurrentDomain.BaseDirectory + "/" + file).ReadToEnd();
Console.WriteLine(file + " 的檔案內容:");
Console.WriteLine(data + "\n");

string raw = "";
for (int i = 0; i < data.Length; i++)
{
    JsonNode node;
    json.TryGetPropertyValue(data[i] + "", out node);
    raw += node.GetValue<String>();
}
Console.WriteLine("壓縮後的編碼:");
for (int i = 0; i < raw.Length; i++)
{
    Console.Write(raw[i]);
    if ((i + 1) % 8 == 0) Console.Write(" ");
}
Console.WriteLine();

if (raw.Length % 8 != 0)
{
    raw += new string[]
    {
        "0","00","000","1110","11110","111101",
"1111010"
    }[7 - raw.Length % 8];
}

var output = file.Substring(0, file.LastIndexOf('.')) + ".bin";
Console.WriteLine("壓縮比: " + (double)raw.Length / (File.ReadAllBytes(file).Length * 8));
Console.WriteLine("壓縮後檔案名稱: " + output);
Console.WriteLine("存入壓縮檔的編碼:");
byte[] bytes = new byte[raw.Length];
for (int i = 0; i < raw.Length; i++)
{
    Console.Write(raw[i]);
    if ((i + 1) % 8 == 0) Console.Write(" ");
    bytes[i] = (byte)(raw[i] - '0');
}

File.WriteAllBytes(AppDomain.CurrentDomain.BaseDirectory + "/" + output, bytes);

Last updated