【问题标题】:Java: Write to a file in UTF-32 FormatJava:以 UTF-32 格式写入文件
【发布时间】:2018-03-22 16:20:47
【问题描述】:

是否可以将字符串写入 utf-32 格式的文件?例如:RandomAccessFile 类仅提供 writeUTF() 方法,该方法以修改后的 UTF-8 格式写入字符串。

假设我的任务是将每个现有的 unicode 字符写入文件:)。

【问题讨论】:

标签: java unicode randomaccessfile


【解决方案1】:

您应该将您的字符串转换为 UTF-32 格式的字节,然后将这些字节写入您的随机文件

RandomAccessFile file = ...
String str = "Hi";
byte[] bytes = str.getBytes("UTF-32");
file.write(bytes);

【讨论】:

    【解决方案2】:

    你可以使用BufferedWriter:

    public class SampleCode {
    
        public static void main(String[] args) throws IOException {
            String aString = "File contents";
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("outfilename"), "UTF-32"));
            try {
                out.write(aString);
            } finally {
                out.close();
            }
    
        }
    }
    

    或者你可以使用

    类似地,java.io.OutputStreamWriter 类充当字符流和字节流之间的桥梁。使用此类创建一个 Writer 以便能够将字节写入文件:

    Writer out = new OutputStreamWriter(new FileOutputStream(outfile), "UTF-32");
    

    或者你也可以使用如下的字符串格式:

    public static String convertTo32(String toConvert){
        for (int i = 0; i < toConvert.length(); ) {
            int codePoint = Character.codePointAt(toConvert, i);
            i += Character.charCount(codePoint);
            //System.out.printf("%x%n", codePoint);
            String utf32 = String.format("0x%x%n", codePoint);
            return utf32;
        }
        return null;
    }
    

    How can I convert UTF-16 to UTF-32 in java?

    【讨论】:

    • 虽然您的第一个解决方案很好,但 convertTo32 存在缺陷,java 中的字符串内部始终具有 UTF16 编码,不能代表其他内容
    • 另外,String utf32 应该声明在循环之上,return utf32; 应该声明在循环之后,否则,根本没有循环的意义。
    • 当你直接使用someone-else's answer时,一定要正确归属,否则称为抄袭。
    猜你喜欢
    • 2012-04-08
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    相关资源
    最近更新 更多