Solved

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

Posted on 2008-10-02
10
212 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
  • 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
 

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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
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

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

760 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now