Solved

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

Posted on 2008-10-01
8
222 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
0
Comment
Question by:Element_T
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 7

Expert Comment

by:humanonomics
ID: 22613716
Is this for some kind of home assignment ?
0
 
LVL 6

Expert Comment

by:manuel_m
ID: 22614116
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
 

Author Comment

by:Element_T
ID: 22614505
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
 
LVL 6

Expert Comment

by:manuel_m
ID: 22615157
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
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.

 
LVL 1

Accepted Solution

by:
verickson earned 500 total points
ID: 22618571
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
 

Author Closing Comment

by:Element_T
ID: 31501937
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
 
LVL 1

Expert Comment

by:verickson
ID: 22619771
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
 

Author Comment

by:Element_T
ID: 22619886
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 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

Join & Write a Comment

Suggested Solutions

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Jaspersoft Studio is a plugin for Eclipse that lets you create reports from a datasource.  In this article, we'll go over creating a report from a default template and setting up a datasource that connects to your database.
This video teaches viewers about errors in exception handling.
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…

758 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

20 Experts available now in Live!

Get 1:1 Help Now