473,385 Members | 1,642 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

problem in deleting the file

149 100+
hi,
in my project...i need to do delete operation..i developed one XML file...when i do delete..it is deleting the whole information in the xml file....what ever value i enter in the jsp page it should take that value and do delete operation...for deleting i wrote servlet coding...here is my code...can anyone help me where i wrote wrong...

delete.java

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. package proj;
  4.  
  5. import java.io.*;
  6. import java.io.IOException;
  7. import java.io.PrintWriter;
  8. import java.util.Properties;
  9. import javax.servlet.*;
  10. import javax.servlet.http.*;
  11. import javax.servlet.ServletException;
  12. import javax.servlet.http.HttpServlet;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15.  
  16. import org.w3c.dom.*;
  17. import javax.xml.parsers.*;
  18. import javax.xml.transform.*;
  19. import javax.xml.transform.dom.*;
  20. import javax.xml.transform.stream.*;
  21.  
  22. public class delete extends HttpServlet {
  23.  
  24.     public void doPost(HttpServletRequest request, HttpServletResponse response)
  25.             throws ServletException, IOException {
  26.  
  27.         response.setContentType("text/html");
  28.         PrintWriter pw = response.getWriter();
  29.         String s = null;
  30.  
  31.         try {
  32.             DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
  33.             DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
  34.  
  35.             // Creating the path for XML File using Properties
  36.             ServletContext servletContextObj = request.getSession().getServletContext();
  37.             String excelTemplatesPath = servletContextObj.getRealPath("/");
  38.             String filePaths = excelTemplatesPath + File.separator
  39.                     + "config.properties";
  40.             Properties propObj = new Properties();
  41.             propObj.load(new FileInputStream(filePaths));
  42.             String gprsLoginPath = null;
  43.             gprsLoginPath = propObj.getProperty("GPRS_LOGIN_PATH");
  44.             if (gprsLoginPath == null || gprsLoginPath.trim().equals("")) {
  45.                 gprsLoginPath = excelTemplatesPath;
  46.             }
  47.             gprsLoginPath += File.separator + "login.xml";
  48.             java.io.File file = new java.io.File(gprsLoginPath);
  49.             Document doc = null;
  50.             if (file.exists()) {
  51.                 try {
  52.                     doc = docBuilder.parse(file);
  53.                 } catch (Exception ex) {
  54.                     doc = docBuilder.newDocument();
  55.                     Element root = doc.createElement("PACKS");
  56.                     doc.appendChild(root);
  57.                 }
  58.             } else {
  59.                 doc = docBuilder.newDocument();
  60.                 // Creating Root Tag
  61.                 Element root = doc.createElement("PACKS");
  62.                 doc.appendChild(root);
  63.             }
  64.  
  65.             // creating a new instance of a DOM to build a DOM tree.
  66.             // Document doc = docBuilder.newDocument();
  67.             delNode(file, doc, "PACK_NAME");
  68.             pw.println("<b>Xml File Deleted Successfully</b>");
  69.         } catch (Exception e) {
  70.             System.out.println(e);
  71.             e.printStackTrace();
  72.         }
  73.     }
  74.  
  75.     public static void delNode(java.io.File file, Node parent, String filter)
  76.             throws Exception {
  77.  
  78.         NodeList children = parent.getChildNodes();
  79.  
  80.         for (int i = 0; i < children.getLength(); i++) {
  81.             Node child = children.item(i);
  82.  
  83.             if (child.getNodeType() == Node.ELEMENT_NODE) {
  84.  
  85.                 if (child.getNodeName().equals(filter)) {
  86.                     parent.removeChild(child);
  87.                 } else {
  88.                     delNode(file, child, filter);
  89.                 }
  90.             }
  91.         }
  92.         // TransformerFactory instance is used to create Transformer objects.
  93.         TransformerFactory factory = TransformerFactory.newInstance();
  94.         Transformer transformer = factory.newTransformer();
  95.         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  96.         // create string from xml tree
  97.         StringWriter sw = new StringWriter();
  98.         StreamResult result = new StreamResult(sw);
  99.         Document doc = null;
  100.         DOMSource source = new DOMSource(doc);
  101.         transformer.transform(source, result);
  102.         String xmlString = sw.toString();
  103.  
  104.         //File file = new File("E:/xgprs/xmlgprs/login.xml");
  105.         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
  106.                 new FileOutputStream(file)));
  107.         bw.write(xmlString);
  108.         bw.flush();
  109.         bw.close();
  110.  
  111.     }
  112. }
  113.  
  114.  
thanks,
madhu.
Jul 21 '10 #1
2 1926
chaarmann
785 Expert 512MB
Why are you using so many dots between your sentences? Do you have so less time that you need to use telegram style? Then the best help is to take more time for solving your problems. Software programming cannot be done quickly and in a hurry, but only through deep thinking and taking time. If you follow this important advice, then you will save time. Yes, you read right, you will save time! You will notice that you will do your job more slowly but finish earlier. Often I was in a situation where there is a big time pressure to finish a program and find a solution to a current problem. When I hastily go into try-and-error or copy-and-paste misunderstood code I didn't achive anything except a chaotic program. When I made a break, breathed deeply and start thinking hard, then suddenly the problem was solved in an instant. I am sure you'll figure out that this tip is worth more than the hundred of tips you will get for your hundred of small problems. Dig a well for a thirsty man instead of always giving him water.

1.) you wrote:
"....what ever value i enter in the jsp page it should take that value and do delete operation..".
So the first conclusion is to check for this value and print it out.
So deep thinking means "If I enter something on the web page, I must make sure that this value is available in my function doPost() where I need it".
The second thought: "If it's there, I should print it out for verification".
But I can't see a print statement here. Also I can't see the command to fetch that value anywhere (by using request.getParameter()).
2.) you wrote: "when i do delete..it is deleting the whole information in the xml file.."
Reduce your code to the minimum code with the problem by commenting out (temporarily) all other code that has nothing to do with the problem. If you think the delNode() method is the problem, then just test it in isolation! You may think "But I am in a hurry and have no time for testing. Let me just assume that it is working the way I think it should. Let me continue messing with the other code". Wrong! Deep thinking means you will make sure it works the way you expect it! So just relax, take a deep breath and start a new program:

Expand|Select|Wrap|Line Numbers
  1. public class HelloWorld {
  2.   public static void main(String[] args) {
  3.     File file = new File("c:\temp\test.xml");
  4.     doc = docBuilder.parse(file);       
  5.     delNode(file, doc, "PACK_NAME");
  6.   }
  7.   public static void delNode(java.io.File file, Node parent, String filter) throws Exception { 
  8.     ...
  9.   }
  10. }
So what happens with file test.xml exactly? Why is it always empty afterwards even if you put some xml-text inside it? I mean after isolating the code you can see it has nothing to do with the browser, jsp-page etc. You could have posted this smaller problem here in the forum to speed up getting a solution and to cause less work for the helpers. You could even help yourself more (and helpers like me) and put in some statements that prints out the xml-code before it gets saved. Deep thinking means "I don't get the result I expected, so let me print out the intermediate results" That means, just insert a System.out.println (xmlString) after line 102! You will see that whatever value you assign as "Node parent" and "String filter", it always is empty! You will ask yourself "Is my input not relevant fr the output? And why is it printing the empty string many times instead of only once in a complex xml-file where a root node has many children?". So go through the source code line by line with a parser (or in your mind). You will probably stop reading at line 88, where the method delNode() calls itself! Bingo! That's why it prints out many lines! You may think "I don't fully understand what it is doing here". So put it on your list as "second problem, to be solved after first problem is solved" and comment out the whole functionality (commenting out line 78 to 91). This is to simplify and isolate your problem more. Recursion is gone now, so you only get one line printed, but still empty! Wait, you should think, when the program still works, then it doesn't need my input "parent" and "filter", and that's the bug! Now try to figure out what is really necessary for your program, but commenting out every line of source code left and try-compiling it. You will come up with these lines left:
Expand|Select|Wrap|Line Numbers
  1. public class HelloWorld {
  2.   public static void main(String[] args) {
  3.     File file = new File("c:\temp\test.xml");
  4.     delNode(file);
  5.   }
  6.   public static void delNode(java.io.File file) throws Exception { 
  7.     TransformerFactory factory = TransformerFactory.newInstance(); 
  8.         Transformer transformer = factory.newTransformer(); 
  9.         StringWriter sw = new StringWriter(); 
  10.         StreamResult result = new StreamResult(sw); 
  11.         Document doc = null; 
  12.         DOMSource source = new DOMSource(doc); 
  13.         transformer.transform(source, result); 
  14.         String xmlString = sw.toString();
  15.         System.out.println(xmlString); 
  16.   }
  17. }
And that's exactly what happens!
You create an DOM-source from a Document that is null, so the DOM-source is empty! Then you transformed your DOM-source to a string which then must be emty! Then you saved the empty string to file, so overwriting the orignal file!
All the other code was irrelevant and distracted you from the problem. By using method "isolation" you figured out the problem yourself!
So how to solve? First, you should not assign a null-document, but the original document that contained your xml-code. Second, you should make sure that you don't overwrite your document each time in every recursive call. So you must split up the function in two: one function that deletes all unwanted nodes from the document by recursively parsing through all child-nodes, and one function that gets the changed document and writes it back to a file.

Summary: follow this advice to solve this (and your future) problems to become a good programmer:
- isolate the problem by commenting out all unnecessary code.
- print the results after each step (or use a debugger where you can see the results after each step).
- don't skip many steps or take too big steps, (no telegram), just think deeply by taking each small step one by one (analysing the code line by line thoroughly.
- No copy-and-paste! Write the code of your own! If you even copy a single line into your code that you don't understand 100%, then this line may cause a big error that you may not immediately detect. So feel responsible for the code. You can't sell a huge and nice apple if it has a small worm hole!
Jul 23 '10 #2
madhuriks
149 100+
hi chaarmann,
thanks for ur reply and suggestion..i'll follow it...and i got solved that problem..thanks a lot..
Jul 23 '10 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: vKp | last post by:
I'm having a problem with file(). If I try to open a url of the form "http://example.com/find?one,two", I get an error of the following form: ....failed to create stream: Bad file descriptor... ...
1
by: Alfons | last post by:
Hello, I have build a program that can do file transferring between a Windows XP computer and a DOS computer via a serial port. The Windows program I have build in C++ with Visual Studio 6.0....
13
by: Bob Darlington | last post by:
I have a repair and backup database routine which runs when a user closes down my application. It works fine in my development machine, but breaks on a client's at the following line: If...
0
by: Bandit | last post by:
I'm populating a gridview (called docList) with document info from a network folder like so: Sub Show_Files(ByVal inputDir As String) Dim strFileNamePath As String = inputDir Dim dirInfo As...
5
by: George | last post by:
VB.net 2003 standard, XP windows home edition. Installed first application OK today. When I removed the application via Control Panel, there were no problems and the app folders were deleted. ...
11
by: Yvonne | last post by:
Hi, I'm running Access 2002 and have a problem deleting records on a continuous form. I thought it might be due to relationships with two other tables but having deleted these relationships,...
6
by: FrankB | last post by:
Hello, after setting another image to the picture box it is not possible to delete the last shown file via File.Delete ( sFilename). Path of image file is correct. Error message box says: file...
1
by: diyasher | last post by:
hello my code is in c#. i am using fileSystemWatcher class to watch event when file is deleted. event is fire when file is deleted, i want to stop deleting file, means when user want to delete...
2
by: andrescasta | last post by:
Hello, i have a problem when i try to delete a file that i recently uploaded. To upload, i used the FileUpload, when i receive the file, i save it in a directory inside the virtual application...
5
krungkrung
by: krungkrung | last post by:
hi again to everyone! I made a simple program(for my VB.Net practice). The program loads an image file to a picturebox upon clicking a button. after loading the image file i have another button to...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.