Java: 以 UTF-32 格式写入文件
Java: Write to a file in UTF-32 Format
是否可以将字符串写入utf-32格式的文件?例如:RandomAccessFile class 只提供了 writeUTF() 方法,它以修改后的 UTF-8 格式写入字符串。
假设我的任务是将每个现有的 unicode 字符写入一个文件:)。
您应该将您的字符串转换为 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();
}
}
}
或者您可以使用
Analogously, the class java.io.OutputStreamWriter acts as a bridge between characters streams and bytes streams. Create a Writer with this class to be able to write bytes to the file:
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;
}
参见 。
是否可以将字符串写入utf-32格式的文件?例如:RandomAccessFile class 只提供了 writeUTF() 方法,它以修改后的 UTF-8 格式写入字符串。
假设我的任务是将每个现有的 unicode 字符写入一个文件:)。
您应该将您的字符串转换为 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();
}
}
}
或者您可以使用
Analogously, the class java.io.OutputStreamWriter acts as a bridge between characters streams and bytes streams. Create a Writer with this class to be able to write bytes to the file:
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;
}
参见