我使用InputStreamReader来读取GBK编码txt,我认为lineTxt也会被GBK编码,但是当我比较"WGS 84 / UTM区域44N“时,它们是相同的。
以下是代码:
1、s是UTF-8编码的字符串。
2、lineTxt是GBK编码的字符串(我不确定,但我知道"read“是GBK)
3我猜"lineTxt = bufferedReader.readLine()“如果编码,将触发转换,但不确定。
try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), ENCODING_GBK);
BufferedReader bufferedReader = new BufferedReader(read)) {
String lineTxt;
while ((lineTxt = bufferedReader.readLine()) != null) {
if (lineTxt.contains("WGS 84 / UTM zone 44N")) {
String s = new String("输出坐标系:WGS 84 / UTM zone 44N".getBytes(), StandardCharsets.UTF_8);
System.out.println(System.getProperty("file.encoding"));
System.out.println(Arrays.toString(s.getBytes()));
System.out.println(Arrays.toString(lineTxt.getBytes()));
}
}
} catch (IOException e) {
log.error("Read file failed");
e.printStackTrace();
}
发布于 2022-08-14 08:36:34
当读取文件并将行存储为字符串对象时,编码将转换为字符串的内部表示形式(UTF-16)。lineTxt.getBytes()
在平台的默认编码中将UTF-16字符串转换为字节数组(这取决于在Windows上的系统区域设置。当你在另一个月台的时候,它将是UTF-8 )。
如果要将文件的内容获取为字节数组(获取GBK表示形式,并且不希望将内容转换为UTF-16),请按以下方式读取该文件:
try {
File file = new File("C:\\tmp\\fileGBK.txt");
byte[] lineTxt = Files.readAllBytes(file.toPath());
System.out.println(Arrays.toString(lineTxt));
} catch (IOException e) {
e.printStackTrace();
}
您将得到GBK ([-54, -28, -77, -10, -41, ...
)中字符串的表示形式。
如果要逐个读取文件中的行并获取行的GBK表示形式:
File file = new File("C:\\tmp\\fileGBK.txt");
final Charset ENCODING_GBK = Charset.forName("GBK");
try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), ENCODING_GBK);
BufferedReader bufferedReader = new BufferedReader(read)) {
String lineTxt;
while ((lineTxt = bufferedReader.readLine()) != null) {
if (lineTxt.contains("WGS 84 / UTM zone 44N")) {
String s = new String("输出坐标系:WGS 84 / UTM zone 44N".getBytes(), StandardCharsets.UTF_8);
System.out.println(System.getProperty("file.encoding"));
System.out.println(Arrays.toString(s.getBytes()));
System.out.println(Arrays.toString(lineTxt.getBytes(ENCODING_GBK)));
}
}
} catch (IOException e) {
e.printStackTrace();
}
https://stackoverflow.com/questions/73045377
复制相似问题