Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 222
  • Last Modified:

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

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
Element_T
Asked:
Element_T
  • 4
  • 4
1 Solution
 
Element_TAuthor Commented:
Please try to give solutions with LineNumberReader anything else is to complicate...
0
 
manuel_mCommented:
Here is a simple example of the LineNumberReader: http://www.javadb.com/using-the-linenumberreader-class

It is not that hard :-)
0
 
manuel_mCommented:
Try it first by yourself and if you are getting stuck we can help you.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
Element_TAuthor Commented:
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
 
manuel_mCommented:
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
 
Element_TAuthor Commented:
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
 
Element_TAuthor Commented:
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
 
manuel_mCommented:
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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now