【问题标题】:UTF to ASCII ConversionUTF 到 ASCII 转换
【发布时间】:2016-06-28 17:51:31
【问题描述】:

我正在使用 Java Web 服务调用 oracle 程序来读取一些记录。这个 Java Web 服务的执行是在 Shell 脚本的帮助下自动执行的。 所以流程是这样的:

Shell 脚本调用 Java Web 服务,进一步 Java Web 服务调用 Oracle 存储过程读取一些记录。

作为最终产品,会生成一个 UTF-8 格式的提要文件,我们需要以 ASCII 格式创建文件。那么任何人都可以帮助我使用一些 Linux 或 Java 代码,我可以将它们添加到我的 shell 脚本或 Java 代码中以将文件转换为 ASCII。

附:我知道在 NOTEPAD++ 的帮助下将文件从 UTF 转换为 ASCII,但我需要这个过程是自动化的。任何帮助将不胜感激。

【问题讨论】:

  • 是 UTF -8 。如果您需要更多信息,请告诉我。
  • 值得注意的是,如果您的所有文本都由 ASCII 字符组成,那么 UTF-8 文件就是一个 ASCII 文件。 (UTF-8 是专门为实现这种兼容性而设计的。)如果它包含非 ASCII 字符,那么这些字符可能会被转换为 ?。您可以通过先compatibility-normalizing 文本来保留其中的一些。
  • 呼应@VGR,您可能需要重新验证从数据库中获取文本并用问号删除一些字符的要求。

标签: java web-services unix ascii utf


【解决方案1】:

可以这样做:

Charset srcEncoding = StandardCharsets.UTF_8;
Charset destEncoding = StandardCharsets.US_ASCII;
try (BufferedReader reader = Files.newBufferedReader(Paths.get("src"), srcEncoding);
     BufferedWriter writer = Files.newBufferedWriter(Paths.get("dest"), destEncoding)) {
    String line;
    while ((line = reader.readLine()) != null) {
        writer.write(line);
        writer.newLine();
    }
}

【讨论】:

【解决方案2】:

理想的解决方案取决于您当前编写文件的方式。 有很多方法。 如果您正在使用字节,您可以使用:

byte[] bytes = "somestring".getBytes("characterSetName");

PrintStream 方法在构造函数中包含一个字符集名称:

new PrintStream(file,"characterSetName");

在您的情况下,字符集名称将是 US-ASCII。

您还可以使用 Charset 实例在字符集之间进行转换。

举个例子:

public static void main(String[] args) throws Exception {
    String textToWrite = "Hello World of encodings...";
    CharBuffer cb1 = CharBuffer.wrap(textToWrite);
    CharBuffer cb2 = CharBuffer.wrap(textToWrite);

    Charset chr = Charset.forName("US-ASCII");
    ByteBuffer byteBuffer = chr.encode(cb1);
    write("CharsetEncode.txt",byteBuffer);

    CharsetEncoder cr = chr.newEncoder();
    ByteBuffer byteBuffer1 = cr.encode(cb2);
    write("CharsetEncoderEncode.txt",byteBuffer1);

    write("StringGetBytes.txt",textToWrite.getBytes("US-ASCII"));

}

public static void write(String name, ByteBuffer buffer) throws Exception {
    byte[] bytes = new byte[buffer.limit()];
    buffer.get(bytes);
    write(name,bytes);
}

public static void write(String name, byte[] bytes) throws Exception {
    File f = new File(name);
    FileOutputStream fos = new FileOutputStream(f);
    fos.write(bytes);
    fos.flush();
    fos.close();
}

使用 BufferedWriter 时,可以使用Files.newBufferedWriter。这允许指定字符集。

File targetFile = ....;
BufferedWriter w = Files.newBufferedWriter(targetFile.toPath(), Charset.forName("US-ASCII"));

【讨论】:

  • 嘿,如果从 UTF-8 转换为 ASCII,Somestring 的值是多少?
  • 如前所述,US-ASCII。
  • 对不起,我没有阅读那部分,somestring 怎么样?是生成的文件名还是生成的文件类型?
  • "somestring" 是文件的文本或内容。最明显的解决方案是首先以正确的编码写入文件,而不是稍后再转换。
  • 因此,如果我希望它首先以 ASCII 格式而不是 UTF 格式编写它,那么最好的方法是什么。现在我正在使用字节来写入文件,它会自动将其写入 UTF-8 格式。
猜你喜欢
  • 1970-01-01
  • 2013-04-19
  • 2010-12-02
  • 2011-08-22
  • 2019-10-31
  • 1970-01-01
  • 2013-12-30
  • 2011-06-26
  • 2011-07-18
相关资源
最近更新 更多