I'm writing a program to dynamically update an xml file to add, delete, and edit entries in the file. I've run into an issue with the add method because when I write into the file, a random letter is added before the line. EX:
I want to add "<item> ..." to the end of the list of entries, but when it is added, this is what is added "Z <item> ..."
The spacing for the <item> is correct, however, I don't see where or why the Z is added.
public static void insertItem(Item i) { try { String insert = "\t\t<item>"; String text = ""; Scanner in = new Scanner(file); while(in.hasNext()) { text = text.concat(in.next()); } int where = findEnd(text); insert += "\n\t\t\t<title>" + i.getTitle() + "</title>\n\t\t\t<description>\n\t\t\t" + i.getDesc() + "\n\t\t\t</description>\n\t\t</item>\n"; System.out.println("\n" + insert); //text = firstPart + insert + secondPart; //System.out.println("\n" + text); StringBuffer str = new StringBuffer(text); str = str.insert(where, insert); //System.out.println(insert); System.out.println(file.length()); insert(file.getPath(), file.length()-20, insert); System.out.println(file.length()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block System.out.println("File not found: " + file.getPath()); } //refreshItems(); } //Returns the index of the '<' in the </channel> statement private static int findEnd(String file) { int index = file.indexOf("</channel>"); return index; } public static void insert(String filename, long offset, String content) { try { RandomAccessFile r = new RandomAccessFile(new File(filename), "rw"); RandomAccessFile rtemp = new RandomAccessFile(new File(filename + "~"), "rw"); long fileSize = r.length(); FileChannel sourceChannel = r.getChannel(); FileChannel targetChannel = rtemp.getChannel(); sourceChannel.transferTo(offset, (fileSize - offset), targetChannel); sourceChannel.truncate(offset); r.seek(offset); r.writeUTF(content); long newOffset = r.getFilePointer(); targetChannel.position(0L); sourceChannel.transferFrom(targetChannel, newOffset, (fileSize - offset)); sourceChannel.close(); targetChannel.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
Relevant file contents before the edit:
<item> <title>Valentine's Day</title> <description> The Sophomore Class Cabinet will be selling Valentine's Day Candy Grams/Special Packages during all lunches starting February 6th until February 12th. </description> </item> </channel>
After
<item> <title>Valentine's Day</title> <description> The Sophomore Class Cabinet will be selling Valentine's Day Candy Grams/Special Packages during all lunches starting February 6th until February 12th. </description> </item> Z <item> <title>chicken</title> <description> noodle </description> </item>