Go Premium for a chance to win a PS4. Enter to Win

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

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

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
0
Element_T
Asked:
Element_T
  • 3
  • 2
  • 2
  • +1
1 Solution
 
humanonomicsCommented:
Is this for some kind of home assignment ?
0
 
manuel_mCommented:
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.
0
 
Element_TAuthor 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

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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

0
 
vericksonCommented:
A better solution would be to use regular expressions or the split funtion in the Pattern class.  You can completely bypass the messy loops you are currently using.  For future reference any time you want to search/replace parts of a string or file, refer to the Pattern and Matcher classes.

I'm unsure of the context your class is being used. However, I think you can adapt the attached code to suit your purposes.
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.regex.*;
 
 
/*
  This is the first comment
*/
 
class RemoveHeader
{
    /*
      Here is the second comment
    */
    public RemoveHeader(String filename, String newFilename) throws IOException
    {
	FileInputStream fis = new FileInputStream(filename);
	FileChannel fc = fis.getChannel();
	
	// Create a read only CharBuffer of the file. 
	// A regular expression will be applied to cbuf.
	ByteBuffer bbuf = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int)fc.size());
	CharBuffer cbuf = Charset.forName("8859_1").newDecoder().decode(bbuf);
 
	String[] fileparts = filename.split("\\.");
	if (fileparts == null)
	{
	    System.out.println("No extensions found");
	    return;
	}
	
	String extension = fileparts[1];  // get extension
	String fileParts[];
	String head;
	String tail;
 
	// Find the first comment
	if (extension.equals("cpp") ||
	    extension.equals("java") ||
	    extension.equals("c"))
	{
	    fileParts = cbuf.toString().split("/\\*", 2);
	    head = fileParts[0];
	    
	    fileParts = fileParts[1].split("\\*/",2);
	    tail = fileParts[1];
        }
	else if (extension.equals("xml") ||
		 extension.equals("xhtml") ||
		 extension.equals("html") ||
		 extension.equals("xsl"))
	{
	    fileParts = cbuf.toString().split("<--", 2);
	    head = fileParts[0];
	    
	    fileParts = fileParts[1].split("-->",2);
	    tail = fileParts[1];
	}
	else
	{
	    System.out.println("Not a recognized extension");
	    return;
	}
 
 
	String contentHeaderRemoved = head+tail;
 
	try 
	{
	    // Write a new file without the header
	    BufferedWriter document = new BufferedWriter(new FileWriter(newFilename));
	    document.write(contentHeaderRemoved);
	    document.close();
	} 
	catch (IOException e) 
	{
	    System.out.println("Error: " + e);
	}
    }
 
    public static void main(String[] args)
    {
	try
	{
	    RemoveHeader rh = new RemoveHeader("RemoveHeader.java", "test.java");
	}
	catch (IOException e)
	{
	}
    }
}

Open in new window

0
 
Element_TAuthor 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.
0
 
vericksonCommented:
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.
0
 
Element_TAuthor 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....
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 3
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now