Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: File editing problem

  1. #1
    Member
    Join Date
    Feb 2012
    Posts
    173
    Thanks
    6
    Thanked 10 Times in 10 Posts

    Question File editing problem

    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>


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: File editing problem

    Is it always the letter Z and in the same location?

    Where in the code does the "Z" first appear? Add some debug statements to test all Strings for "Z" and to print that String when it is found.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Feb 2012
    Posts
    173
    Thanks
    6
    Thanked 10 Times in 10 Posts

    Default Re: File editing problem

    Quote Originally Posted by Norm View Post
    Is it always the letter Z and in the same location?

    Where in the code does the "Z" first appear? Add some debug statements to test all Strings for "Z" and to print that String when it is found.
    No, it is not always a Z and it is always in the same location. There isn't anywhere in the code that a random letter like that should show up. Aside from the Item class, all code used in that method is present and posted.

    Here is the Item class for future reference, I also do have println statements for debugging active.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: File editing problem

    Can you make a Short, Self Contained, Correct Example for testing?

    What's in the file that is being written to? Does the code skip over one character that appears as a random character?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Feb 2012
    Posts
    173
    Thanks
    6
    Thanked 10 Times in 10 Posts

    Default Re: File editing problem

    XML Editor.zip

    Attached is a ZIP file containing all the files in the project, assuming you are using Eclipse, you can right click on the file manager in Eclipse and import the file system after you unzip it. The Class being tested is called "Translator."

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: File editing problem

    Sorry, I don't want the full code. I don't use eclipse.
    Can you make a Short, Self Contained, Correct Example for testing?
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member
    Join Date
    Feb 2012
    Posts
    173
    Thanks
    6
    Thanked 10 Times in 10 Posts

    Default Re: File editing problem

    Code to run

     
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.nio.channels.FileChannel;
    import java.util.Scanner;
     
    public class Item {
     
    	String title;
    	String description;
    	static String directory = "C:\\Users\\Alex\\workspace\\XML Editor\\"; //change this to the directory where the .xml file is located
    	static String name = "test.xml"; //change this to the name of the .xml file
    	static File file = new File(directory + name);
    	public Item(String title, String description)
    	{
    		this.title = title;
    		this.description = description;
    	}
     
    	public String getTitle()
    	{
    		return title;
    	}
     
    	public String getDesc()
    	{
    		return description;
    	}
     
    	public void setDesc(String desc)
    	{
    		description = desc;
    	}
     
    	public void setTitle(String title)
    	{
    		this.title = title;
    	}
    	public static void insertItem(Item i) 
    	{
    		try {
    			String insert = "\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</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()-18, 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();
    		}
    	}
     
    	public static void main(String[] args)
    	{
    		insertItem(new Item("chicken", "noodle"));
    	}
     
    }

    test .xml file

    <rss xmlns:media="www.hardytechsolutions.com" version="2.0">
    	<channel>
    		<title>BMHS Daily Announcements</title>
    		<link />
    		<description>Daily Announcements displayed on TV's</description>
    		<language>en-US</language>
    		<copyright>Copyright (c) 2013 William Hardy</copyright>
    		<pubDate>Tue, 03 Dec 2013 07:05:52 -0500</pubDate>
    		<ttl>1</ttl>
    		<item>
    			<title>Library Reservations</title>
    			<description>
    				Period 7 (9:00-10:10 am) reserved ~ OPEN with limited
    				access, Period 5
    				(12:08–1:42 pm) reserved ~ OPEN with limited access,
    				After School ~
    				CLOSED for Math Power Hour.
    			</description>
    		</item>
    		<item>
    			<title>Math Power Hour</title>
    			<description>
    				this week will take place today from 3:15 to 4:15 in the
    				school library.
    			</description>
    		</item>
    		<item>
    			<title>Senior Retreat</title>
    			<description>
    				Your retreat is tomorrow! Please arrive to the Fine Arts
    				Gym by 8am.
    				Dress for the day is casual, but you need to wear your
    				senior
    				t-shirt.
    			</description>
    		</item>
    		<item>
    			<title>Saturday Detention</title>
    			<description>
    				This Saturday, 2/8/14, is a scheduled Saturday
    				Detention. Reminder
    				emails have been sent to student email accounts
    				and to parents.
    			</description>
    		</item>
    		<item>
    			<title>CPR and First Aid</title>
    			<description>
    				There will be CPR and First Aid classes offered
    				Wednesday, February 5 and
    				Monday, February 24. The classes will be in
    				Room 201 and will start
    				promptly at 3:30.
    			</description>
    		</item>
    		<item>
    			<title>Student Tech Club</title>
    			<description>
    				Bishop McNamara is looking for students who are
    				interested in how
    				technology influences their lives. Please contact
    				Ms. Auchmoody or
    				Mr. Buckley.
    			</description>
    		</item>
    		<item>
    			<title>Passport Future</title>
    			<description>
    				Seniors, please remember to apply for the Passport to
    				the Future Award.
    				Essays are due to Mr. Pozniak or Mr. Williams by
    				Feb. 6th.
    			</description>
    		</item>
    		<item>
    			<title>Boys' Lacrosse</title>
    			<description>
    				There will be a parents meeting for all boys' lacrosse
    				players on Monday,
    				February 10.
    			</description>
    		</item>
    		<item>
    			<title>Music Trip</title>
    			<description>
    				It is time to sign up for your Hotel Rooms for the
    				Chicago Trip.
    			</description>
    		</item>
    		<item>
    			<title>Guidance counselors</title>
    			<description>
    				will be visiting your English classrooms on Monday and
    				Tuesday, February
    				10 and 11, to distribute the 2014-2015 Course
    				Bulletin booklets and
    				Course Selection Sheets.
    			</description>
    		</item>
    		<item>
    			<title>Talent Show</title>
    			<description>
    				practice will be today from 3:15 to 4:30. Please be on
    				time in room 218.
    			</description>
    		</item>
    		<item>
    			<title>Engineering Club</title>
    			<description>
    				will not be meeting this week. Robotics team needs to
    				start work on
    				RobotC as soon as possible.
    			</description>
    		</item>
    		<item>
    			<title>Adventure Sports Club</title>
    			<description>
    				is meeting today promptly at 3:15 in Room 108. We will
    				be talking
    				about our next two trips so please be on time.
    			</description>
    		</item>
    		<item>
    			<title>Honors Global Studies</title>
    			<description>
    				Applications are now available on the BMHS website under
    				"Academics/Course
    				Bulletin."
    			</description>
    		</item>
    		<item>
    			<title>Missing Camera</title>
    			<description>
    				We need assistance in locating a Black, Nikon camera
    				with a Silver and
    				Black case that has Nikon written on the front.
    			</description>
    		</item>
    		<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>
    </rss>

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: File editing problem

    Can you make a much smaller test.xml file so its easier to see what happens.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Member
    Join Date
    Feb 2012
    Posts
    173
    Thanks
    6
    Thanked 10 Times in 10 Posts

    Default Re: File editing problem

    All the changes are made at the bottom of the file.

    <rss xmlns:media="www.hardytechsolutions.com" version="2.0">
    	<channel>
    		<title>BMHS Daily Announcements</title>
    		<link />
    		<description>Daily Announcements displayed on TV's</description>
    		<language>en-US</language>
    		<copyright>Copyright (c) 2013 William Hardy</copyright>
    		<pubDate>Tue, 03 Dec 2013 07:05:52 -0500</pubDate>
    		<ttl>1</ttl>
    		<item>
    			<title>Library Reservations</title>
    			<description>
    				Period 7 (9:00-10:10 am) reserved ~ OPEN with limited
    				access, Period 5
    				(12:08–1:42 pm) reserved ~ OPEN with limited access,
    				After School ~
    				CLOSED for Math Power Hour.
    			</description>
    		</item>
    		<item>
    			<title>Math Power Hour</title>
    			<description>
    				this week will take place today from 3:15 to 4:15 in the
    				school library.
    			</description>
    		</item>
    </channel>
    </rss>

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: File editing problem

    What is the -18 for?
    	insert(file.getPath(), file.length()-18, insert);
    Can you make a minimum sized .xml file? Maybe 5 lines.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Member
    Join Date
    Feb 2012
    Posts
    173
    Thanks
    6
    Thanked 10 Times in 10 Posts

    Default Re: File editing problem

    The -18 is the offset from the end of the file to put the addition inside the <channel> element.

    technically, this should work.

    this week will take place today from 3:15 to 4:15 in the
    				school library.
    			</description>
    		</item>
    </channel>
    </rss>

    The addition should appear right after the </item> line

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: File editing problem

    Having a hardcoded value is a poor technique.

    Here's what I'm testing with:
    X</channel>
    </rss>

    The debug print out:
    before len=19
    offset=1 fSize=19 content.len=3
    after len=24

    I added this line before the call to insert():
             insert = "YYY";                      //<<<<<<<<<<<<<<<
    	 insert(file.getPath(), file.length()-18, insert);     //??????????-18
    None of the rest of the code is needed for testing. The problem is in the insert() method. Look at the output file in a hexeditor to see what is inserted.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Editing a Text File in Java, a specific part.
    By sakonpure6 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: December 22nd, 2013, 03:32 PM
  2. Working on reading / editing file data for my program.. Need HELP!
    By travis07 in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: December 14th, 2013, 04:04 AM
  3. Editing this code so that it takes a file instead of a string
    By tomb1992 in forum What's Wrong With My Code?
    Replies: 9
    Last Post: March 4th, 2013, 10:21 AM
  4. [Help] Problem with Class arrays, adding/editing and deleting
    By Grant_Searle in forum Object Oriented Programming
    Replies: 7
    Last Post: December 16th, 2011, 10:10 AM
  5. I/O stream for reading and editing a file full of numbers
    By Harry Blargle in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: October 5th, 2011, 09:00 AM

Tags for this Thread