【问题标题】:RandomAccessFile writing non-printable characters/newlines when writing regular text to a file将常规文本写入文件时,RandomAccessFile 写入不可打印字符/换行符
【发布时间】:2021-12-20 22:32:15
【问题描述】:

我正在尝试使用 RandomAccessFile 写入现有文件,但是对 writer.writeUTF() 的调用会用不可打印字符或换行符覆盖写入偏移之前的两个字符。我真的不知道是什么导致了这个问题,并且我进行了多次搜索,但没有任何结果。

        File mapObjects = new File(args[0] + "/data/maps/objects");
        ArrayList<String> warpNames = new ArrayList<String>();
        ArrayList<Integer> offsets = new ArrayList<Integer>();
        for (File mapObject : mapObjects.listFiles()) {
            try {
                Scanner reader = new Scanner(mapObject);
                int offset = 0;
                String ln = new String();
                System.out.println(mapObject.getPath());
                while (!ln.contains("def_warps_to")) { // will loop until it finds the definition of the warp name
                    offset += ln.length();
                    ln = reader.nextLine();
                }
                offset += 28;
                warpNames.add(ln.substring(14)); // adds the "warps_to" token to the list
                offsets.add(offset);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        Collections.shuffle(warpNames); // randomize
        for (String s : warpNames)
            System.out.println(s);
        int i = 0; // iterator of warpNames and offsets
        for (File mapObject : mapObjects.listFiles()) {
            try {
                RandomAccessFile writer = new RandomAccessFile(mapObject, "rw");
                writer.seek(offsets.get(i));
                writer.writeUTF(warpNames.get(i)); // overwrites "warps_to" token with randomized one
                i++;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

【问题讨论】:

  • 始终阅读文档,不要仅凭名称就假设方法的作用。 Read about writeUTF()
  • 始终关闭您的扫描仪和写入器。未能关闭它们可能导致资源泄漏;未能关闭 writer 也可能导致文件内容不完整。

标签: java io randomaccessfile non-printing-characters


【解决方案1】:

我修好了,我所要做的就是打电话

writer.writeBytes(warpNames.get(i))

而不是

writer.writeUTF(warpNames.get(i))

【讨论】:

    猜你喜欢
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多