zoukankan      html  css  js  c++  java
  • C#和JAVA文件的UTF8格式互换

    web项目用JAVA写,安装程序用C#写成,安装时需要利用C#程序读取.java文件,该文件编码格式是UTF-8,一开始这样来读写JAVA文件的:
          using (StreamReader sr =
              new StreamReader(new FileStream(filePath, FileMode.Open),
              System.Text.Encoding.UTF8))
       {
        using (StreamWriter sw =
               new StreamWriter(new FileStream(newFile, FileMode.Create),
               System.Text.Encoding.UTF8))
        {
         string line = "";
         while ((line = sr.ReadLine()) != null)
         {
          for (int i = 0; i < args.Length; i++)
          {
           if (line.Contains(args[i]))
           {
            if (!line.Contains("=")) break;
            int offset = line.IndexOf('=');
            string replacedStr = line.Substring(offset + 1);
            line = line.Replace(replacedStr, " " + values[i] + ";");
           }
          }
          sw.WriteLine(line);
         }
        }
       }

    结果发现生成的JAVA文件总是含有乱码,后来调研得知:

    使用 Encoding.UTF8 是自动带 三 byte 的 BOM,如果要不添加 BOM。应该改用 UTF8Encoding utf8 = new UTF8Encoding(是否添加 BOM);

    而JAVA文件的头中不包含这三个字节的BOM,因此C#源码改为如下一切恢复正常:

    UTF8Encoding utf8 = new UTF8Encoding(false);

       using (StreamReader sr =
        new StreamReader(new FileStream(filePath, FileMode.Open),
        utf8))
       {
        using (StreamWriter sw =
         new StreamWriter(new FileStream(newFile, FileMode.Create),
         utf8))
        {
         string line = "";
         while ((line = sr.ReadLine()) != null)
         {
          for (int i = 0; i < args.Length; i++)
          {
           if (line.Contains(args[i]))
           {
            if (!line.Contains("=")) break;
            int offset = line.IndexOf('=');
            string replacedStr = line.Substring(offset + 1);
            line = line.Replace(replacedStr, " " + values[i] + ";");
           }
          }
          sw.WriteLine(line);
         }
         sr.Close();
         sw.Close();
        }
       }

  • 相关阅读:
    Two strings CodeForces
    Dasha and Photos CodeForces
    Largest Beautiful Number CodeForces
    Timetable CodeForces
    Financiers Game CodeForces
    AC日记——整理药名 openjudge 1.7 15
    AC日记——大小写字母互换 openjudge 1.7 14
    AC日记——将字符串中的小写字母换成大写字母 openjudge 1.7 13
    AC日记——加密的病历单 openjudge 1.7 12
    AC日记——潜伏着 openjudge 1.7 11
  • 原文地址:https://www.cnblogs.com/pricks/p/1575465.html
Copyright © 2011-2022 走看看