处理文件时的 Java 问题

标签 java string replace replaceall

我在尝试从字符串中删除子序列 \u000 时遇到一些问题。

首先,我通过 String str = new String(bytes, "UTF8"); 从文件中将字节 [] 读入字符串,然后我得到 str ,它等于 \u0004Word ,这意味着 4Word4 是单词Word 的长度。所以现在我需要将其转换为常规的 4WordsreplaceAll("\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 时简单地丢弃数组中的初始字节,使用接受 offsetlen 参数的构造函数。

如果您碰巧确实在字符串中包含所有这些字符,那么只需使用 substring 来删除最初的 6 个字符就足够了。

关于处理文件时的 Java 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26284707/

相关文章:

javascript - 替换console.log等字符串中的变量

java - 从 URL 读写图像

java - 告诉浏览器应该将 Servlets xml 输出视为 RSS

java - HashMap 中的键排序是什么?

java - 从大小发生变化的字符串中检索子字符串

javascript - 正则表达式

regex - 如何从 R 公式字符串中删除系数

python - 使用 python 替换日期列中缺少的月份和年份

java - 如何将米转换为英里,并以英尺和英寸为单位给出余数?

javascript - 如何替换字符串中的所有空格