我在尝试从字符串中删除子序列 \u000
时遇到一些问题。
首先,我通过 String str = new String(bytes, "UTF8");
从文件中将字节 [] 读入字符串,然后我得到 str
,它等于 \u0004Word
,这意味着 4Word
。 4
是单词Word
的长度。所以现在我需要将其转换为常规的 4Words
。 replaceAll("\u000", "");
、replaceALL("\\\\u000", "")
等不起作用。如何做到这一点?
void FillingStorage() throws Exception{
Path path = Paths.get(System.getProperty("db.file"));//that's my file
byte[] data = Files.readAllBytes(path);
String str = new String(data, "UTF8");
System.out.println(str);
String res = str.replaceAll("I don't know what to write here cos nothing I've tried works");
return;
}
更新!
首先,我用 Key -> Value 和 Key1 -> Value1
填充 HashMap。然后我将其作为字节写入文件中。
因此,当我尝试将其转换回字符串并打印时,我看到:Key Value Key1 Value1
而不是 3Key 5Value 4Key1 6Value1
。但令人惊讶的是,如果你查看我打印的字符串,你会看到类似这样的内容: \u0003Key\u0005Value 等...
所以看起来我的字符串包含这些数字,但 java 无法打印它们。
这就是我在文件中写入字节的方式:
DataOutputStream stream = new DataOutputStream(new FileOutputStream(System.getProperty("db.file"), true));
for (Map.Entry<String, String> entry : storage.entrySet()) {
byte[] bytesKey = entry.getKey().getBytes(StandardCharsets.UTF_8);
stream.write((int)bytesKey.length);//it disappears!
stream.write(bytesKey);
byte[] bytesVal = entry.getValue().getBytes(StandardCharsets.UTF_8);
stream.write((Integer)bytesVal.length);//disappears too!
stream.write(bytesVal);
}
stream.close();
最佳答案
首先,您的要求不需要正则表达式,因此您应该使用 replace()
来代替。
其次,\uxxxx
是Java中的字 rune 字语法,因此不清楚字符串中是否确实包含字符\
u
0
0
0
;更合乎逻辑的是,您的字节数组只是以等于 4 的单个字节开始,即字符串长度。
在这种情况下,您应该在转换为 String
时简单地丢弃数组中的初始字节,使用接受 offset
和 len
参数的构造函数。
如果您碰巧确实在字符串中包含所有这些字符,那么只需使用 substring
来删除最初的 6 个字符就足够了。
关于处理文件时的 Java 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26284707/