Solved

Need a Urgent Help, removing the first comment in all supplied files in java

Posted on 2008-10-02
10
218 Views
Last Modified: 2012-05-05
I need an urgent help in follow case:

two java.io.File object in constructor as input and output and a method which performs replacement.
- the replacement must take into account the file ending of the input file:
  + for .java, .cpp, .c and .css remove the FIRST occurrence of "/* ... */"
  + for .xml, .xhtml, .html and .xsl remove the FIRST occurrence of "<!-- ... -->"
  + all other files should be untouched
- note that the comment strings could be anywhere in a line, in sinlge or multiple lines


PLEASE TRY TO GIVE A SOLUTION WITH LINENUMBERREADER:-)
package com.communology.tools.cvsheader;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import org.apache.tools.ant.types.FileSet;
 
 
 
public class RemoveHeader {
 
    private static File java;
 
    private File toDir;
 
    private List<FileSet> filesets = new ArrayList<FileSet>();
 
    private List<String> includes = new ArrayList<String>();
    private List<String> excludes = new ArrayList<String>();
 
    private String charset;
 
    public RemoveHeader() {}
    
 
    // File input, File output
    public RemoveHeader(String charset, List<String> excludes, List<FileSet> filesets, List<String> includes, File Input, File Output) {
        super();
        this.charset = charset;
        this.setExcludes(excludes);
        this.setFilesets(filesets);
        this.setToDir(Input);
    }
 
        public static void main(String[] args) {
            RemoveHeader r1 = new RemoveHeader();
            RemoveHeader r2 = new RemoveHeader();
            RemoveHeader r3 = new RemoveHeader();
 
            r2.removeCommentFromFile("//RemoveHeader.java", "//Test.java", "/*");
 
            String charset = "UTF-8";
    
            
            
   
    //        r1.removeCommentFromFile("test1.txt", "test2.txt","2");        
    //      r3.removeCommentFromFile("test1.txt", "test2.txt","<!");       
    //        String[] exclude = {"*.java","*.c","*.cpp"};
    //        String[] include = {"*.xml","*.xhtml"};
    //        List<String> includesa = new ArrayList<String>();
    //        List<String> excludesa = new ArrayList<String>();
    //        includesa.addAll(includesa);
    //        excludesa.addAll(exclude);
    //        FileSet fs = new FileSet();
    //        List<FileSet> lfs = new ArrayList<FileSet>();
    //        File in = new File ("");
    //        RemoveHeader rh = new RemoveHeader(charset,excludesa,lfs,includesa,in);
    //        DirectoryScanner ds = new DirectoryScanner();
    //        ds.addExcludes(exclude);
    //        ds.setIncludes(include);
    //        ds.scan();
         
         
        }
 
    /**
     * Defines the directory where to save the replaced files. This is a
     * mandatory parameter.
     * 
     * @param toDir the directory where to save files
     */
    public void setTodir(File toDir) {
        this.setToDir(toDir);
    }
 
    /**
     * Defines the character encoding used for reading and writing files.
     * 
     * @param charset a valid character encoding for the current Java platform
     */
    public void setCharset(String charset) {
        this.charset = charset;
    }
 
    public void removeCommentFromFile(File inputFile, File outputFile, String comment) {
 
        try {
 
            //Construct the new file that will later be renamed to the original filename.
            //            File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
 
            BufferedReader br = new BufferedReader(new FileReader(inputFile));
            PrintWriter pw = new PrintWriter(new FileWriter(outputFile));
 
            String line = null;
 
            //            while ((line = br.readLine())!=null) {
            //                if (!line.trim().startsWith(comment)) {
            //                    pw.println(line);
            //                    pw.flush();
            //                }
            //            }
            int found = -1;
            while ((line = br.readLine()) != null) {
                // check if you find the closing tag
                // closing tag depending on file ending. this one is fix now! change it.
                // 
                if (found == 1 && line.trim().indexOf("*/") > -1) {
                    found = 0;
                }
                // comments will not printed because the found value is 1.
                // when we found the closing comment it is set back to 0 and the text will be printed again.
                else if (found < 1 && !line.trim().startsWith(comment)) {
                    pw.println(line);
                    pw.flush();
                } else {
                    // check if we have already found a comment. if not then set to 1
                    // else take old value. should be 0.
                    found = found == -1 ? 1 : found;
                }
            }
 
            pw.close();
            br.close();
 
            //            if (!tempFile.renameTo(inFile))
            //                System.out.println("Could not rename file");
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
 
    // getter and setter
 
    public void setIncludes(List<String> includes) {
        this.includes = includes;
    }
 
    public List<String> getIncludes() {
        return includes;
    }
 
    public void setExcludes(List<String> excludes) {
        this.excludes = excludes;
    }
 
    public List<String> getExcludes() {
        return excludes;
    }
 
    public void setFilesets(List<FileSet> filesets) {
        this.filesets = filesets;
    }
 
    public List<FileSet> getFilesets() {
        return filesets;
    }
 
    public void setToDir(File toDir) {
        this.toDir = toDir;
    }
 
    public File getToDir() {
        return toDir;
    }
 
}

Open in new window

0
Comment
Question by:Element_T
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
10 Comments
 

Author Comment

by:Element_T
ID: 22622478
Please try to give solutions with LineNumberReader anything else is to complicate...
0
 
LVL 6

Expert Comment

by:manuel_m
ID: 22622534
Here is a simple example of the LineNumberReader: http://www.javadb.com/using-the-linenumberreader-class

It is not that hard :-)
0
 
LVL 6

Expert Comment

by:manuel_m
ID: 22622538
Try it first by yourself and if you are getting stuck we can help you.
0
Transaction Monitoring Vs. Real User Monitoring

Synthetic Transaction Monitoring Vs. Real User Monitoring: When To Use Each Approach? In this article, we will discuss two major monitoring approaches: Synthetic Transaction and Real User Monitoring.

 

Author Comment

by:Element_T
ID: 22622595
how I can search in the folder dynamical for xml or css file, ...etc...for parsing and remove the comments...
package com.communology.tools.cvsheader;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import org.apache.tools.ant.types.FileSet;
 
 
 
public class RemoveHeader {
 
    private File toDir;
 
    private List<FileSet> filesets = new ArrayList<FileSet>();
 
    private List<String> includes = new ArrayList<String>();
    private List<String> excludes = new ArrayList<String>();
 
    private String charset;
 
    public RemoveHeader() {}
    
 
    // File input, File output
    public RemoveHeader(String charset, List<String> excludes, List<FileSet> filesets, List<String> includes, File Input, File Output) {
        super();
        this.charset = charset;
        this.setExcludes(excludes);
        this.setFilesets(filesets);
        this.setToDir(Input);
    }
 
        public static void main(String[] args) {
            RemoveHeader r1 = new RemoveHeader();
            RemoveHeader r2 = new RemoveHeader();
            RemoveHeader r3 = new RemoveHeader();
 
            File in = new File("Test3.java");
            File out = new File("Test.java");
            r2.removeCommentFromFile(in, out, "/*");
 
            String charset = "UTF-8";
    
            
            
   
    //        r1.removeCommentFromFile("test1.txt", "test2.txt","2");        
    //      r3.removeCommentFromFile("test1.txt", "test2.txt","<!");       
    //        String[] exclude = {"*.java","*.c","*.cpp"};
    //        String[] include = {"*.xml","*.xhtml"};
    //        List<String> includesa = new ArrayList<String>();
    //        List<String> excludesa = new ArrayList<String>();
    //        includesa.addAll(includesa);
    //        excludesa.addAll(exclude);
    //        FileSet fs = new FileSet();
    //        List<FileSet> lfs = new ArrayList<FileSet>();
    //        File in = new File ("");
    //        RemoveHeader rh = new RemoveHeader(charset,excludesa,lfs,includesa,in);
    //        DirectoryScanner ds = new DirectoryScanner();
    //        ds.addExcludes(exclude);
    //        ds.setIncludes(include);
    //        ds.scan();
         
         
        }
 
    /**
     * Defines the directory where to save the replaced files. This is a
     * mandatory parameter.
     * 
     * @param toDir the directory where to save files
     */
    public void setTodir(File toDir) {
        this.setToDir(toDir);
    }
 
    /**
     * Defines the character encoding used for reading and writing files.
     * 
     * @param charset a valid character encoding for the current Java platform
     */
    public void setCharset(String charset) {
        this.charset = charset;
    }
//    public void readFromFile(String filename) {
//        
//        LineNumberReader lineNumberReader = null;
//        
//        try {
//            
//            //Construct the LineNumberReader object
//            lineNumberReader = new LineNumberReader(new FileReader(filename));
//            
//            String line = null;
//            
//            while ((line = lineNumberReader.readLine()) != null) {
//                
//                System.out.println("Line " + lineNumberReader.getLineNumber() +
//                        ": " + line);
//            }
//            
//            
//        } catch (FileNotFoundException ex) {
//            ex.printStackTrace();
//        } catch (IOException ex) {
//            ex.printStackTrace();
//        } finally {
//            //Close the BufferedWriter
//            try {
//                if (lineNumberReader != null) {
//                    lineNumberReader.close();
//                }
//            } catch (IOException ex) {
//                ex.printStackTrace();
//            }
//        }
//    }
//    
    public void removeCommentFromFile(File inputFile, File outputFile, String comment) {
        LineNumberReader lnr=null;
 
        try {
 
            //Construct the new file that will later be renamed to the original filename.
            //            File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
            lnr=new LineNumberReader(new FileReader(inputFile));
            
            BufferedReader br = new BufferedReader(new FileReader(inputFile));
            PrintWriter pw = new PrintWriter(new FileWriter(outputFile));
 
            String line = null;
 
            //            while ((line = br.readLine())!=null) {
            //                if (!line.trim().startsWith(comment)) {
            //                    pw.println(line);
            //                    pw.flush();
            //                }
            //            }
            int found = -1;
            while ((line = br.readLine()) != null) {
                // check if you find the closing tag
                // closing tag depending on file ending. this one is fix now! change it.
                // 
                if (found == 1 && line.trim().indexOf("*/") > -1) {
                    found = 0;
                }
                // comments will not printed because the found value is 1.
                // when we found the closing comment it is set back to 0 and the text will be printed again.
                else if (found < 1 && !line.trim().startsWith(comment)) {
                    pw.println(line);
                    pw.flush();
                } else {
                    // check if we have already found a comment. if not then set to 1
                    // else take old value. should be 0.
                    found = found == -1 ? 1 : found;
                }
            }
 
            pw.close();
            br.close();
 
            //            if (!tempFile.renameTo(inFile))
            //                System.out.println("Could not rename file");
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
 
    // getter and setter
 
    public void setIncludes(List<String> includes) {
        this.includes = includes;
    }
 
    public List<String> getIncludes() {
        return includes;
    }
 
    public void setExcludes(List<String> excludes) {
        this.excludes = excludes;
    }
 
    public List<String> getExcludes() {
        return excludes;
    }
 
    public void setFilesets(List<FileSet> filesets) {
        this.filesets = filesets;
    }
 
    public List<FileSet> getFilesets() {
        return filesets;
    }
 
    public void setToDir(File toDir) {
        this.toDir = toDir;
    }
 
    public File getToDir() {
        return toDir;
    }
 
}

Open in new window

0
 
LVL 6

Expert Comment

by:manuel_m
ID: 22622687
With the listFiles method from java.io.File: http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#listFiles(java.io.FileFilter)

See the code for comments.
File searchDir = new File("C:/dir");
            // list all files in this directory...
            // with the FileFilter you can control what files or directories should
            // be listed.
            File[] listedFiles = searchDir.listFiles(new FileFilter() {
                public boolean accept(File pathname) {
                    // check for file ending. other endings have to be added!
                    if (pathname.isFile() && pathname.getName().endsWith(".css")) {
                        return true;
                    }
                    return false;
                }
            });
            // check if the listedFiles is not null or empty
            if (null != listedFiles && listedFiles.length > 0) {
                // now iterate over the listedFiles and call your method.
                for(File file : listedFiles) {
                    // ...
                }
            }

Open in new window

0
 

Author Comment

by:Element_T
ID: 22622822
How I can search in a specific folder where I put files with .java/.css/.xml etc and  
+ for .java, .cpp, .c and .css remove  FIRST occurrence of "/* ... */"
+ for .xml, .xhtml, .html and .xsl remove the FIRST occurrence of "<!-- ... -->"
0
 

Author Comment

by:Element_T
ID: 22622831
here my actual code
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
import java.io.BufferedReader;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import org.apache.tools.ant.types.FileSet;
 
 
 
public class RemoveHeader {
 
    private File toDir;
 
    private List<FileSet> filesets = new ArrayList<FileSet>();
 
    private List<String> includes = new ArrayList<String>();
    private List<String> excludes = new ArrayList<String>();
 
    private String charset;
 
    public RemoveHeader() {}
    
 
    // File input, File output
    public RemoveHeader(String charset, List<String> excludes, List<FileSet> filesets, List<String> includes, File Input, File Output) {
        super();
        this.charset = charset;
        this.setExcludes(excludes);
        this.setFilesets(filesets);
        this.setToDir(Input);
    }
 
        public static void main(String[] args) {
            RemoveHeader r1 = new RemoveHeader();
            RemoveHeader r2 = new RemoveHeader();
            RemoveHeader r3 = new RemoveHeader();
 
            File in = new File("Test3.java");
            File out = new File("Test.java");
            r2.removeCommentFromFile(in, out, "/*");
 
            String charset = "UTF-8";
            File searchDir = new File("//:/dir");
            // list all files in this directory...
            // with the FileFilter you can control what files or directories should
            // be listed.
            File[] listedFiles = searchDir.listFiles(new FileFilter() {
                public boolean accept(File pathname) {
                    // check for file ending. other endings have to be added!
                    if (pathname.isFile() && pathname.getName().endsWith(".java")) {
                        return true;
                    }
                    return false;
                }
            });
            // check if the listedFiles is not null or empty
            if (null != listedFiles && listedFiles.length > 0) {
                // now iterate over the listedFiles and call  method.
                for(File file : listedFiles) {
                    // ...
                    r1.removeCommentFromFile(in, out, "/*");
                }
            }
 
            
            
   
//            r1.removeCommentFromFile("test1.txt", "test2.txt","2");        
//          r3.removeCommentFromFile("test1.txt", "test2.txt","<!");       
//            String[] exclude = {"*.java","*.c","*.cpp"};
//            String[] include = {"*.xml","*.xhtml"};
//            List<String> includesa = new ArrayList<String>();
//            List<String> excludesa = new ArrayList<String>();
//            includesa.addAll(includesa);
//            excludesa.addAll(exclude);
//            FileSet fs = new FileSet();
//            List<FileSet> lfs = new ArrayList<FileSet>();
//            File in = new File ("");
//            RemoveHeader rh = new RemoveHeader(charset,excludesa,lfs,includesa,in);
//            DirectoryScanner ds = new DirectoryScanner();
//            ds.addExcludes(exclude);
//            ds.setIncludes(include);
//            ds.scan();
         
         
        }
 
    /**
     * Defines the directory where to save the replaced files. This is a
     * mandatory parameter.
     * 
     * @param toDir the directory where to save files
     */
    public void setTodir(File toDir) {
        this.setToDir(toDir);
    }
 
    /**
     * Defines the character encoding used for reading and writing files.
     * 
     * @param charset a valid character encoding for the current Java platform
     */
    public void setCharset(String charset) {
        this.charset = charset;
    }
 
    public void removeCommentFromFile(File inputFile, File outputFile, String comment) {
        LineNumberReader lnr=null;
 
        try {
 
            //Construct the new file that will later be renamed to the original filename.
            //            File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
            lnr=new LineNumberReader(new FileReader(inputFile));
            
            BufferedReader br = new BufferedReader(new FileReader(inputFile));
            PrintWriter pw = new PrintWriter(new FileWriter(outputFile));
 
            String line = null;
 
            //            while ((line = br.readLine())!=null) {
            //                if (!line.trim().startsWith(comment)) {
            //                    pw.println(line);
            //                    pw.flush();
            //                }
            //            }
            int found = -1;
            while ((line = br.readLine()) != null) {
                // check if you find the closing tag
                // closing tag depending on file ending. this one is fix now! change it.
                // 
                if (found == 1 && line.trim().indexOf("*/") > -1) {
                    found = 0;
                }
                // comments will not printed because the found value is 1.
                // when we found the closing comment it is set back to 0 and the text will be printed again.
                else if (found < 1 && !line.trim().startsWith(comment)) {
                    pw.println(line);
                    pw.flush();
                } else {
                    // check if we have already found a comment. if not then set to 1
                    // else take old value. should be 0.
                    found = found == -1 ? 1 : found;
                }
            }
 
            pw.close();
            br.close();
 
            //            if (!tempFile.renameTo(inFile))
            //                System.out.println("Could not rename file");
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
 
    // getter and setter
 
    public void setIncludes(List<String> includes) {
        this.includes = includes;
    }
 
    public List<String> getIncludes() {
        return includes;
    }
 
    public void setExcludes(List<String> excludes) {
        this.excludes = excludes;
    }
 
    public List<String> getExcludes() {
        return excludes;
    }
 
    public void setFilesets(List<FileSet> filesets) {
        this.filesets = filesets;
    }
 
    public List<FileSet> getFilesets() {
        return filesets;
    }
 
    public void setToDir(File toDir) {
        this.toDir = toDir;
    }
 
    public File getToDir() {
        return toDir;
    }
 
}

Open in new window

0
 
LVL 6

Accepted Solution

by:
manuel_m earned 500 total points
ID: 22622900
In the FileFilter you could add the .xml and .css file ending to be included (line 58).

In line 68 you then could check what file ending it is and then depending on the file ending call your removeCommentFromFile method to remove the specified comment value.

You already have the solution in your code. You just have to add some cases depending on the comment type or file ending.
if you remove a line with "/*" then you have to check where the closing of the comment is "*/".
If you remove a comment that starts with "<!--" then you have to search for the closing "-->".

File ending:
if file ends with .css then comments starts with "<!--" and ends with "-->". etc.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question