We help IT Professionals succeed at work.

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

Element_T
Element_T asked
on
293 Views
Last Modified: 2013-12-14
I have to create a java class which accepts 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
Comment
Watch Question

Is this for some kind of home assignment ?

Commented:
For the basics look you could read Sun's Java tutorial at http://java.sun.com/docs/books/tutorial/

Read file line by line:
http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml

By reading line by line you have to search for the first occurrence of "/*...*/" or "<!--...-->" depending on the file ending.

Create the class and the methods. If you are getting stuck come back and post where you have problems.

Author

Commented:
At first thanks a lot...for your help...but..I need a quick help...dont have time to read so much stuff...:-)
I am sorry...
so I create some code...what do yu think...what is the next step...?
Now, I can replace // comments from a text file...but I need a
solution for follow problem...
+ for .java, .cpp, .c and .css remove the FIRST occurrence of "/* ...
*/"
+ for .xml, .xhtml, .html and .xsl remove the FIRST occurrence of
"<!-- ...


I create flowing code....


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>();
 
    @SuppressWarnings("unused")
    private String charset;
 
    public RemoveHeader() {
        // TODO Auto-generated constructor stub
    }
 
    /**
     * @param charset
     * @param excludes
     * @param filesets
     * @param includes
     * @param mappingFile
     * @param mappings
     * @param toDir
     */
 
    // File input, File output
    public RemoveHeader(String charset, List<String> excludes,
List<FileSet> filesets, List<String> includes, File Input) {
        super();
        this.charset = charset;
        this.setExcludes(excludes);
        this.setFilesets(filesets);
        this.setToDir(Input);
    }
    public static void main(String[] args) {
//        String charset = "UTF-8";
//        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();
//        rh.removeCommentFromFile("test.txt", "/*");
        RemoveHeader rh = new RemoveHeader();
        rh.removeCommentFromFile("test.txt", "//");
    }
 
    /**
     * 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(String file, String comment) {
 
        try {
 
            File inFile = new File(file);
 
            if (!inFile.isFile()) {
                System.out.println("Parameter is not an existing
file");
                return;
            }
 
            //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(file));
            PrintWriter pw = new PrintWriter(new
FileWriter(tempFile));
 
//            String lineToRemove = line;
 
            //Read from the original file and write to the new
            //unless content matches data to be removed.
            String line = null;
 
            while ((line = br.readLine())!=null) {
                if (!line.trim().startsWith(comment)) {
                    pw.println(line);
                    pw.flush();
                }
            }
            pw.close();
            br.close();
 
//            //Delete the original file
//            if (!inFile.delete()) {
//                System.out.println("Could not delete file");
//                return;
//            }
 
            //Rename the new file to the filename the original file
had.
            if (!tempFile.renameTo(inFile))
                System.out.println("Could not rename file");
 
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    } 

Open in new window

Commented:
Ok. In line 108 where your while loop is you should set a new int variable that will be set, if you found a line that starts with "/*" or "<!--" .
You could set the initial value to -1 and if you found the first comment you could set the value to 1. After you have found the closing comment you could set the value to 0, so you know you already found the first comment in this text.

Now you have to check what kind of file type it is and set depending on this the closing comment...
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;
  }
}

Open in new window

This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
as first thanks a lot....for this quick help...
as second I dont know this imports can you tell me something about the imports ....
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.regex.
import java.nio.*;
This is another library for more advanced input output options.
It is needed to use Bytebuffer and CharBuffer. (lines 24 and 25)

import java.nio.channels.*;
This is needed for FileChannel. (line 20)

import java.nio.charset.*;
This is needed for charset. (line 25)

import java.util.regex.*;
Whoops. I forgot to remove this import. For this particular code, this isn't needed and can be removed. However, if you want to use regular expressions in the Pattern and Matcher class, you need this library. For your particular problem String splits work well enough.

Author

Commented:
Hi again, thank you...this special import looking very helpful...have to learn more about this import.
You wrote:
"I'm unsure of the context your class is being used. However, I think you can adapt the attached code to suit your purposes."
Here is the context if its help...:


Please create an Ant task for removing the first comment in all supplied files.
- create classes in project folder in package".."
- have a look at "..." for an
example for an Ant task and at the ant doc at "--"
- first create a plain class which accepts 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
- when this is done, create a second class, which extends
org.apache.tools.ant.Task and accepts similar input as ReplaceMappings class
- IMPORTANT: the original source files must never be changed!
- class names: RemoveHeader,  RemoveHeaderTask

The problem is...I am a intermediate beginner in java and have no idea of ANT....
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.