【发布时间】:2018-03-22 16:20:47
【问题描述】:
是否可以将字符串写入 utf-32 格式的文件?例如:RandomAccessFile 类仅提供 writeUTF() 方法,该方法以修改后的 UTF-8 格式写入字符串。
假设我的任务是将每个现有的 unicode 字符写入文件:)。
【问题讨论】:
-
UTF-32LE 还是 UTF-32BE ?
标签: java unicode randomaccessfile
是否可以将字符串写入 utf-32 格式的文件?例如:RandomAccessFile 类仅提供 writeUTF() 方法,该方法以修改后的 UTF-8 格式写入字符串。
假设我的任务是将每个现有的 unicode 字符写入文件:)。
【问题讨论】:
标签: java unicode randomaccessfile
您应该将您的字符串转换为 UTF-32 格式的字节,然后将这些字节写入您的随机文件
RandomAccessFile file = ...
String str = "Hi";
byte[] bytes = str.getBytes("UTF-32");
file.write(bytes);
【讨论】:
你可以使用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;
}
【讨论】:
convertTo32 存在缺陷,java 中的字符串内部始终具有 UTF16 编码,不能代表其他内容
String utf32 应该声明在循环之上,return utf32; 应该声明在循环之后,否则,根本没有循环的意义。