简体   繁体   中英

RandomAccessFile writing non-printable characters/newlines when writing regular text to a file

I am trying to write to an existing file with RandomAccessFile, but the call to writer.writeUTF() overwrites the two characters before the write offset with non-printable characters or newlines. I genuinely do not know what is causing this problem, and I have done multiple searches which turned up nothing.

        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();
            }
        }

I fixed it, all I had to do was call

writer.writeBytes(warpNames.get(i))

instead of

writer.writeUTF(warpNames.get(i))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM