Hack Forums
[Java] append a file in java in specific line - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Java] append a file in java in specific line (/showthread.php?tid=6012778)



append a file in java in specific line - blackcoder00 - Oct 1, 2019

i wanna create some new compiler for html language like when i type
PHP Code

<?php 
<repeat it="5">
<
input type="text" name="user">
</
repeat> 
it will repeat the line of input 5 time and write it in a file and deleting the last 3 line and replace it with : 5 input so my problem is when i replace those line and write it in the file the compiler of netbean display to me this error message :


Quote: Exception in thread "AWT-EventQueue-0" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at htmleditor.editfr.boomActionPerformed(editfr.java:145)
at htmleditor.editfr.access$100(editfr.java:28)
at htmleditor.editfr$2.actionPerformed(editfr.java:72)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6539)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6304)
at java.awt.Container.processEvent(Container.java:2239)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2297)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)
at java.awt.Container.dispatchEventImpl(Container.java:2283)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
at java.awt.EventQueue$4.run(EventQueue.java:733)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)


Code :
PHP Code

<?php 
private void boomActionPerformed(java.awt.event.ActionEvent evt) {                                     
    
// TODO add your handling code here:
     
String p = name.getText()+".html";
     
int iteranum = 0;
     
String linetow;
     
String word = null;
    
Scanner scan = null;
    try {
        
scan = new Scanner(new File(p));
    } catch (
FileNotFoundException ex) {
        
Logger.getLogger(editfr.class.getName()).log(Level.SEVERE, null, ex);
    }
    while(
scan.hasNext()){
        
String line = scan.nextLine().toLowerCase().toString();
        if(
line.contains("<repeat")){
            
int i= line.indexOf("it=")+4;
            
char itera = line.charAt(i);
            
iteranum=Integer.parseInt(String.valueOf(itera));  
        }
         
linetow = scan.nextLine().toLowerCase().toString();

         
System.out.println(p);
        for(
int j=1;j<=iteranum;j++){
            
//begin

        
line = line.replace(line, linetow);
        try {

Files.write(Paths.get(p), line.getBytes(), StandardOpenOption.APPEND);
     }
        catch (
IOException e) {
//exception handling left as an exercise for the reader
    
}
            
//end
        
}
    }
} 



RE: append a file in java in specific line - pointandlaugh - Oct 2, 2019

(Oct 1, 2019 01:45 PM)blackcoder00 Wrote:  i wanna create some new compiler for html language like when i type
PHP Code

<?php 
<repeat it="5">
<
input type="text" name="user">
</
repeat> 
it will repeat the line of input 5 time and write it in a file and deleting the last 3 line and replace it with : 5 input so my problem is when i replace those line and write it in the file the compiler of netbean display to me this error message :



Code :
PHP Code

<?php 
private void boomActionPerformed(java.awt.event.ActionEvent evt) {                                     
    
// TODO add your handling code here:
 
    String p = name.getText()+".html";
 
    int iteranum = 0;
 
    String linetow;
 
    String word = null;
 
   Scanner scan = null;
 
   try {
 
       scan = new Scanner(new File(p));
 
   } catch (FileNotFoundException ex) {
 
       Logger.getLogger(editfr.class.getName()).log(Level.SEVERE, null, ex);
 
   }
 
   while(scan.hasNext()){
 
       String line = scan.nextLine().toLowerCase().toString();
 
       if(line.contains("<repeat")){
 
           int i= line.indexOf("it=")+4;
 
           char itera = line.charAt(i);
 
           iteranum=Integer.parseInt(String.valueOf(itera));  
        
}
 
        linetow = scan.nextLine().toLowerCase().toString();

 
        System.out.println(p);
 
       for(int j=1;j<=iteranum;j++){
 
           //begin

 
       line = line.replace(line, linetow);
 
       try {

Files.write(Paths.get(p), line.getBytes(), StandardOpenOption.APPEND);
 
    }
 
       catch (IOException e) {
//exception handling left as an exercise for the reader
 
   }
 
           //end
 
       }
 
   }
} 
                  

Quick aside on data structures... The thing with HTML/XML trees is that it's an entire tree object rather than just lines in a file. You might be better off using SAX to parse your file properly and building your own tree to output after you're done expanding all your custom elements out rather than trying to be clever and doing it on the fly, it'll be much easier and more maintainable. For example, I can see a break in this one if I did something like

PHP Code

<?php 
<repeat it="4">
<
div>
it will only pick up and print the opening div tag
</div>
</
repeat> 

With that out of the way, think about how the OS stores and controls access to files. The scanner object has locked the file for its own purposes, and you've just tried to open another file descriptor on it, it's probably booted you out to stop messy data reads.


RE: append a file in java in specific line - MavenGradle - Oct 4, 2019

(Oct 1, 2019 01:45 PM)blackcoder00 Wrote:  
PHP Code

<?php 
private void boomActionPerformed(java.awt.event.ActionEvent evt) {                                     
    
// TODO add your handling code here:
 
    String p = name.getText()+".html";
 
    int iteranum = 0;
 
    String linetow;
 
    String word = null;
 
   Scanner scan = null;
 
   try {
 
       scan = new Scanner(new File(p));
 
   } catch (FileNotFoundException ex) {
 
       Logger.getLogger(editfr.class.getName()).log(Level.SEVERE, null, ex);
 
   }
 
   while(scan.hasNext()){
 
       String line = scan.nextLine().toLowerCase().toString();
 
       if(line.contains("<repeat")){
 
           int i= line.indexOf("it=")+4;
 
           char itera = line.charAt(i);
 
           iteranum=Integer.parseInt(String.valueOf(itera));  
        
}
 
        linetow = scan.nextLine().toLowerCase().toString();

 
        System.out.println(p);
 
       for(int j=1;j<=iteranum;j++){
 
           //begin

 
       line = line.replace(line, linetow);
 
       try {

Files.write(Paths.get(p), line.getBytes(), StandardOpenOption.APPEND);
 
    }
 
       catch (IOException e) {
//exception handling left as an exercise for the reader
 
   }
 
           //end
 
       }
 
   }
} 
                  

This is not a valid way to do this at all. You are using a comparison method that will not work if you type your XML structured code like this:
Code
<RePeaT It="00005">
<input type="text" name="user">
</repeat>
So many things can go wrong with a comparison like that. It's also not very extensible at all and will require you to put so much time into extending your functionality and code in case you ever want another option instead of repeating.

What you need to do is build yourself a tree of whatever it is you're trying to achieve, with certain rules, like for example a repeat operation does not allow another repeat operation inside of it (you should actually allow this, but simply for demonstration purposes). You need to build this virtually in a structured tree. It will be a lot of work to set this up, but in the end you'll have a solid and robust system to do what you're looking to do. If you'd do it right, you can build this to be very extensive.

So in effect what you'd be looking for is made up out of abstract classes in java that you can use to parse your XML objects to classes in which you can then perform the logic that is required. XML can effectively be turned into Java objects using a JAXB implementation. I would not use SAX or DOM for this because first of all DOM is very tedious work, it allows for extreme fine-tuning, of course but it will take up a lot of your time which could be spent on other things (that is if you're making this as if it was business-grade). The SAX approach involves more code and more complexity than any JAXB approach. You'll have to get involved with the parsing of the document.

Just in case, if that's not clear enough, here's an example of what such a tree-like model could look like in Java code:

Code
public abstract class Car implements CarMethods {
}

public class Mercedes extends Car {
@Override
public void drive() {
 // Driving logic
}
@Override
public void brake() {
 // Braking logic here
}
}

public interface CarMethods {
void drive();
void brake();
}

Also, the reason why your code fails is because of, well a lot of things but specifically because right here you don't check if there's even a next line to read:

Code
linetow = scan.nextLine().toLowerCase().toString();



RE: append a file in java in specific line - blackcoder00 - Oct 4, 2019

(Oct 4, 2019 11:11 AM)MavenGradle Wrote:  This is not a valid way to do this at all. You are using a comparison method that will not work if you type your XML structured code like this:
Code
<RePeaT It="5">
<input type="text" name="user">
</repeat>
So many things can go wrong with a comparison like that. It's also not very extensible at all and will require you to put so much time into extending your functionality and code in case you ever want another option instead of repeating.

What you need to do is build yourself a tree of whatever it is you're trying to achieve, with certain rules, like for example a repeat operation does not allow another repeat operation inside of it (you should actually allow this, but simply for demonstration purposes). You need to build this virtually in a structured tree. It will be a lot of work to set this up, but in the end you'll have a solid and robust system to do what you're looking to do. If you'd do it right, you can build this to be very extensive.

So in effect What you'd be looking for is made up out of abstract classes in java that you can use to parse your XML objects to classes in which you can then perform the logic that is required. XML can effectively be turned into Java objects using a JAXB implementation. I would not use SAX or DOM for this because first of all DOM is very tedious work, it allows for extreme fine-tuning, of course but it will take up a lot of your time which could be spent on other things (that is if you're making this as if it was business-grade). The SAX approach involves more code and more complexity than any JAXB approach. You'll have to get involved with the parsing of the document.

Just in case, ff that's not clear enough, here's an example of what such a tree-like model could look like in Java code:

Code
public abstract class Car implements CarMethods {
}

public class Mercedes extends Car {
@Override
public void drive() {
 // Driving logic
}
@Override
public void brake() {
 // Braking logic here
}
}

public interface CarMethods {
void drive();
void brake();
}

dude it's not xml 😁 just i create a new tag for html that can repeat tags like i want


RE: append a file in java in specific line - MavenGradle - Oct 4, 2019

(Oct 4, 2019 01:58 PM)blackcoder00 Wrote:  dude it's not xml  😁 just i create a new tag for html that can repeat tags like i want

You are not simply creating a new tag for HTML, you are inventing your own markup language or as I see it, an XML (EXTENSIBLE Markup language FYI) document which contains HTML elements to keep things very simple and do-able. As such, you should code your interpreter in a way so that it reacts to the elements in an appropriate way. We have provided two ways to do so correctly, efficiently and having extensibility (SAX, JAXB and even DOM so make that three), yet you remain constant in your desire to use contains which has many flaws in a scenario like this. Your code is a testament to that, do note the comment pointandlaugh left behind.

If all you want to do is manipulate HTML you could simply write that in JavaScript (because JavaScript was invented for making websites interactive) like so:
Code
for (let i = 0; i < 4; i++) {
  const para = document.createElement("p");
  const node = document.createTextNode("This is pararaph " + i);
  para.appendChild(node);
  document.getElementById("divAdd").appendChild(para);
)

If instead you want to go full-fledged with this custom markup language of yours, you might want to start looking not at interpreting but at actually compiling which is what you wanted right? You can do so by using lexical analysis tools such as JavaCC or Antlr because like I said, you're not just adding a tag to HTML, you're making your own language:
https://javacc.org/
https://www.antlr.org/

You're asking for the proper way to do this, well you've got it. Anything less is simply sub-par and a testament to your logical thinking skills as a programmer. I expect to see a fully fledged Antlr or JavaCC parser by the end of this if what you say you want is really what you want. Or go ahead and write your own language recognition tool if you want to take it another step further. Again, like pointandlaugh and myself pointed out, contains is not gonna cut it. I'll eagerly await your lexical analyzer.

If you still don't understand, I recommend that you give the following thread a read:
https://hackforums.net/showthread.php?tid=5991114&pid=58845735#pid58845735
https://hackforums.net/showthread.php?tid=5991114&pid=58845964#pid58845964
https://hackforums.net/showthread.php?tid=5991114&pid=58848422#pid58848422
https://hackforums.net/showthread.php?tid=5991114&pid=58853776#pid58853776


RE: append a file in java in specific line - pointandlaugh - Oct 4, 2019

(Oct 4, 2019 01:58 PM)blackcoder00 Wrote:  dude it's not xml  😁 just i create a new tag for html that can repeat tags like i want

There's absolutely no reason you can't use another library to make your life easier, my dude. You're not just "adding a tag", you're adding an element to a tree structure and if you don't write your code to reflect that you're going to see some really fiddly breaks as your code gets more complicated. Highly recommend the links MavenGradle has posted above, they'll help you get it right.

If you want to have a look how other libraries do templating like what you're trying to do, I'd suggest having a look at Thymeleaf. It's my go to templating language if I'm building a spring boot site.