如何在序列化文件中读取和编辑文本?

时间:2014-03-06 17:46:29

标签: java serialization readfile

我有一个被序列化并写入文件的对象。

在将文件序列化回对象实例之前,我想恶意编辑文件中的txt。

    //FILE TAMPER
    //Lexical block: Tamper
    {
        String output = null;
        //Lexical block make output
        {
            LinkedList<String> lls = new LinkedList<String>();
            //Lexical block: Reader
            {
                BufferedReader br = new BufferedReader(new FileReader(fileString));
                while (br.ready()) {
                    String readLine = br.readLine();
                    lls.add(readLine);
                }
                br.close();
            }
            //Lexical block: manipulate
            {
                //Henry Crapper
                final String[] llsToArray = lls.toArray(new String[lls.size()]);
                for (int i = 0; i < llsToArray.length; i++) {
                    String line = llsToArray[i];
                    if (line.contains("Henry")) {
                        line = line.replace("Henry",
                                            "Fsekc");
                        llsToArray[i] = line;
                    }
                    if (line.contains("Crapper")) {
                        line = line.replace("Crapper",
                                            "Dhdhfie");
                        llsToArray[i] = line;
                    }

                    lls = new LinkedList<String>(Arrays.asList(llsToArray));
                }
            }

            //Lexical block: write output
            {
                StringBuilder sb = new StringBuilder();
                for (String string : lls) {
                    sb.append(string).append('\n');
                }
                output = sb.toString();
            }
        }
        //Lexical block: Writer
        {
            BufferedWriter bw = new BufferedWriter(new FileWriter(fileString));
            bw.write(output);
            bw.close();
        }
    }

但是编辑后的文件不正确并且有一些不寻常的字符。

//Before
¨Ìsr&Snippets.Parsed.EmployeeSerialization0I
bankBalanceLnametLjava/lang/String;xp•Åt
Henry Crappe

//After
ÔøΩÔøΩsr&Snippets.Parsed.EmployeeSerialization0I
bankBalanceLnametLjava/lang/String;xpÔøΩÔøΩt
Fsekc Dhdhfie

我猜是存在某种不可读的字符问题?


Answer continued in a new question is here

1 个答案:

答案 0 :(得分:1)

包含序列化对象实例的文件是二进制文件:您不应使用BufferedWriter对其进行编辑。例如,使用RandomAccessFile编辑它。

如果您想知道为什么,Writer中使用的字符集无法与一个字节一对一映射。保存所有文件也会改变意外的位置。