Solved

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

Posted on 2008-10-02
10
215 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
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
web services creation SOAP vs REST 5 56
Windows 10 IE Certificate Issue 10 51
by zero exception 10 52
Cisco ASA: Java web start no go, asdm launcher no go 3 37
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
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 will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

860 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