gpt4 book ai didi

java - 我的(字符串).split ("=");不工作吗?

转载 作者:行者123 更新时间:2023-12-01 18:10:31 24 4
gpt4 key购买 nike

我想将字符串转换为 String[],但它没有按照我希望的方式工作!我的代码:

    public static void get(HashMap<String, String> saves, File file) throws UnsupportedEncodingException, FileNotFoundException, IOException{
if (!file.exists()){
return;
}
InputStreamReader reader;
reader = new InputStreamReader(new FileInputStream(file), "UTF-16");
String r = null;
String[] s;
BufferedReader bufreader = new BufferedReader(reader);
while((r=bufreader.readLine()) != null){
s = r.split("=");
if (s.length < 2){
System.out.println(s.length);
System.out.println(s[0]);
return;
}
saves.put(s[0].toString(), s[1].toString());
s = null;
}
}

当我告诉它将字符串打印到控制台时

System.out.println(s.length);
System.out.println(s[0]);

它只是打印:

1
??????????????????
-
-

它应该读取什么(文件中有什么):

1=welcome
2=hello
3=bye
4=goodbye

所以我希望它将值放入 HashMap 中:

saves.put("1", "welcome");
saves.put("2", "hello");
saves.put("3", "bye");
saves.put("4", "goodbye");

但是 s = e.split("=") 没有拆分它,而是将字符串转换为“?????????”谢谢!

最佳答案

您似乎使用了错误的编码。您的输入文件实际上并不是 Java 代码所期望的 UTF-16

我将您的示例数据保存在一个文件中,结果同样被破坏。

我的系统上的默认编码是UTF-8,因此我使用以下命令更改了文件的编码:

iconv -f utf-8 -t utf-16 orig.txt > converted.txt

converted.txt 上使用您的程序时,它产生预期的输出。

如果我使用orig.txt,它也会产生预期的输出,并在您的程序中进行以下简单的更改:

reader = new InputStreamReader(new FileInputStream(file), "UTF-8");

您可以确保文件是 UTF-16 编码的,如果没有,则将其转换,或者在创建 InputStreamReader 时使用正确的编码。

关于java - 我的(字符串).split ("=");不工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33401491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com