Help Help, I am intermediate in Java...need help in follow case

E

ElementX

There is two java classes
second class is for execute ant file.

First Class does the most.
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
"<!-- ...
-->"

has any body have an example class to do it?

Thanks a lot...if you can help...I create a class but is not
working...maybe I can post it here...
 
R

RedGrittyBrick

ElementX said:
There is two java classes
second class is for execute ant file.

First Class does the most.
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
"<!-- ...
-->"

has any body have an example class to do it?

Thanks a lot...if you can help...I create a class but is not
working...maybe I can post it here...

Do post it here. It would help if you explain *exactly* what you mean by
"is not working".
 
E

ElementX

Do post it here. It would help if you explain *exactly* what you mean by
"is not working".
sorry, the code is creating in an another case, is not working in this
case, but
the main function is the same.
have to read a directory on the pc and remove the comments in the java
classes with
ant app...my question is how I can create java class, which can search
a directory for .java, .cpp, .c and .css file,
get file from directory,
save it in stack ,
and search in the file for comments,
remove the comments
and save the actual in an another folder without a comment ...thats
all...

If you can help it would be great...
 
E

ElementX

Do post it here. It would help if you explain *exactly* what you mean by
"is not working".

the following code was wrote for mappings in jar file...maybe can
help...
public class RemoveHeader extends Task {

private File toDir;

private File mappingFile;

private List<FileSet> filesets;

private List<String> includes, excludes;

private ClassMappings mappings;

private String charset;

/* (non-Javadoc)
* @see org.apache.tools.ant.Task#init()
*/
@Override
public void init() throws BuildException {
super.init();
includes = new ArrayList<String>();
excludes = new ArrayList<String>();
filesets = new ArrayList<FileSet>();
mappings = new ClassMappings();
}

/**
* 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.toDir = toDir;
}

/**
* Defines the location of the mapping file generated by
ProGuard. This
* is a mandatory parameter.
*
* @param mappingFile the file containing the class name
mappings
*/
public void setMappingfile(File mappingFile) {
this.mappingFile = mappingFile;
}

/**
* Defines the configuration files to scan for class names and
to replace
* the original class names with their mappings. XML files are
scanned for
* elements having an attribute named &quot;class&quot;. These
classes will
* be included in the list of classes to replace. Further
classes may be
* added using the &lt;include&gt; directive of this task.
* <p>
* This parameter is mandatory.
*
* @param files the file set containing the files to scan
*/
public void addConfiguredFileSet(FileSet files) {
this.filesets.add(files);
}

/**
* Adds a class name to exclude from the replacement process.
*
* @param name the <code>ClassNames</code> to exclude from the
replacement
*/
public void addConfiguredExclude(ClassNames name) {

excludes.addAll(Arrays.asList(name.getNames()));
}

/**
* Adds a class name to include into the replacement process.
*
* @param name the <code>ClassNames</code> to include into the
replacement
*/
public void addConfiguredInclude(ClassNames name) {

includes.addAll(Arrays.asList(name.getNames()));
}

/**
* 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;
}

/* (non-Javadoc)
* @see org.apache.tools.ant.Task#execute()
*/
@Override
public void execute() throws BuildException {

/* Check input parameters. */
if (filesets.isEmpty()) {
throw new BuildException("No file set defined");
}
if (toDir == null) {
throw new BuildException("No destination directory
defined.");
}
if (mappingFile == null) {
throw new BuildException("No mapping file defined");
}
if (!toDir.exists()) {
throw new BuildException("Destination directory \"" +
toDir.getAbsolutePath() + "\" does not
exist.");
}
if (!mappingFile.exists()) {
throw new BuildException("Mapping file does not
exist");
}
mappings.reset();

/* Search input files for classes to replace. */
findClasses();

/* Parse the ProGuard mappings file. */
try {
mappings.parseMappings(mappingFile);
} catch (IOException ex) {
throw new BuildException("Error parsing mappings file:
" +
mappingFile.getAbsolutePath(), ex);
}

/* Exclude the files that were requested to exclude. */
for (String exclude : excludes) {
if (mappings.removeClass(exclude)) {
log("Excluding \"" + exclude + "\" from replace",
Project.MSG_VERBOSE);
} else {
log("Exclude class \"" + exclude + "\" not found
in the " +
"configuration files", Project.MSG_WARN);
}
}

/* Add includes. */
for (String include : includes) {
mappings.addClass(include);
log("Including \"" + include + "\" into replace",
Project.MSG_VERBOSE);
}

/* Perform the replacement and display results. */
MappingResult result = replace();

if (result.hasFailures()) {
log("Failed to replace the following classes: " +
result.getFailures(),
Project.MSG_WARN);
}
log("Replaced " + result.getMappingsCount() + " mappings",
Project.MSG_INFO);
}

/**
* Searches for classes to replace in the configured file
sets.
*/
private void findClasses() throws BuildException {

/* Loop through all file sets. */
for (FileSet fileset : filesets) {

DirectoryScanner scanner =
fileset.getDirectoryScanner();
String[] files = scanner.getIncludedFiles();
File base = scanner.getBasedir();

for (int i = 0; i < files.length; i++) {

try {
File f = new File(base, files);

if (!f.exists()) {
throw new BuildException("File " +
f.getAbsolutePath() + " not found");
}
log("Searching " + f.getAbsolutePath() + " for
class attributes", Project.MSG_VERBOSE);
mappings.findClasses(f);
} catch (IOException ex) {
throw new BuildException("I/O error parsing
file " + files, ex);
}
}
}
}

/**
* Performs the replace on all files sets of this.
*/
private MappingResult replace() {

MappingResult result = new MappingResult();

/* Loop through all file sets. */
for (FileSet fileset : filesets) {

DirectoryScanner scanner =
fileset.getDirectoryScanner();
String[] files = scanner.getIncludedFiles();
File src = scanner.getBasedir();

for (int i = 0; i < files.length; i++) {

try {
File in = new File(src, files);
File out = new File(toDir, files);

if (!in.exists()) {
throw new BuildException("File " +
in.getAbsolutePath() + " not found");
}
if (!out.getParentFile().exists()) {
out.getParentFile().mkdirs();
}
log("Processing " + in.getAbsolutePath(),
Project.MSG_VERBOSE);
mappings.replaceClassNames(in, out, charset,
result);
} catch (IOException ex) {
throw new BuildException("I/O error replacing
file " + files, ex);
}
}
}

return result;
}
}






}
 
R

RedGrittyBrick

ElementX said:
the following code was wrote for mappings in jar file...maybe can
help...

[code omitted]

If you wrote that then you are skilled enough in Java that you don't
need my help.


If I were tackling the assignment you describe, I would not start with
the code you posted. I'd start from scratch.


Assuming you didn't in fact write the code you posted, you might find
Patricia's guide helpful:
http://home.earthlink.net/~patricia_shanahan/beginner.html

I'd start with the requirement "first create a plain class which accepts
two java.io.File object in constructor as input". From this I'd write

class ReplaceFirstComment {
ReplaceFirstComment(File input, File output) {
// TODO
}
}

Then I'd compile it and test it. I'd not move on until I was entirely
happy with the test results and had eliminated any compiler warnings.

Then I'd think about the next tiny change that I could make that I could
compile and test.
 
E

ElementX

the following code was wrote for mappings in jar file...maybe can
help...

[code omitted]

If you wrote that then you are skilled enough in Java that you don't
need my help.

If I were tackling the assignment you describe, I would not start with
the code you posted. I'd start from scratch.

Assuming you didn't in fact write the code you posted, you might find
Patricia's guide helpful:http://home.earthlink.net/~patricia_shanahan/beginner.html

I'd start with the requirement "first create a plain class which accepts
two java.io.File object in constructor as input". From this I'd write

     class ReplaceFirstComment {
         ReplaceFirstComment(File input, File output) {
             // TODO
         }
     }

Then I'd compile it and test it. I'd not move on until I was entirely
happy with the test results and had eliminated any compiler warnings.

Then I'd think about the next tiny change that I could make that I could
compile and test.

The code is not from me, it was send me as example...it was in the
project folder...as example...yes is not from myself...don't
know...who create it...you are right with your assume...
 
E

ElementX

the following code was wrote for mappings in jar file...maybe can
help...

[code omitted]

If you wrote that then you are skilled enough in Java that you don't
need my help.

If I were tackling the assignment you describe, I would not start with
the code you posted. I'd start from scratch.

Assuming you didn't in fact write the code you posted, you might find
Patricia's guide helpful:http://home.earthlink.net/~patricia_shanahan/beginner.html

I'd start with the requirement "first create a plain class which accepts
two java.io.File object in constructor as input". From this I'd write

     class ReplaceFirstComment {
         ReplaceFirstComment(File input, File output) {
             // TODO
         }
     }

Then I'd compile it and test it. I'd not move on until I was entirely
happy with the test results and had eliminated any compiler warnings.

Then I'd think about the next tiny change that I could make that I could
compile and test.

Do you have an idea...or an example file...which can help more
 
R

RedGrittyBrick

ElementX said:
ElementX said:
On Oct 1, 12:42 pm, RedGrittyBrick <[email protected]>
wrote:
ElementX wrote:
There is two java classes
second class is for execute ant file.
First Class does the most.
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
"<!-- ...
-->"
has any body have an example class to do it?
Thanks a lot...if you can help...I create a class but is not
working...maybe I can post it here...
Do post it here. It would help if you explain *exactly* what you mean by
"is not working".
[code omitted]

If you wrote that then you are skilled enough in Java that you don't
need my help.

If I were tackling the assignment you describe, I would not start with
the code you posted. I'd start from scratch.

Assuming you didn't in fact write the code you posted, you might find
Patricia's guide helpful:http://home.earthlink.net/~patricia_shanahan/beginner.html

I'd start with the requirement "first create a plain class which accepts
two java.io.File object in constructor as input". From this I'd write

class ReplaceFirstComment {
ReplaceFirstComment(File input, File output) {
// TODO
}
}

Then I'd compile it and test it. I'd not move on until I was entirely
happy with the test results and had eliminated any compiler warnings.

Then I'd think about the next tiny change that I could make that I could
compile and test.

Do you have an idea...or an example file...which can help more

My idea was you take my starting point (above) and build on it step by step.

Here's how I imagined proceeding ...

----------------------------------------------------
C:\temp>type ReplaceFirstComment.java
class ReplaceFirstComment {
ReplaceFirstComment(File input, File output) {
// TODO
}
}

C:\temp>javac ReplaceFirstComment.java
ReplaceFirstComment.java:2: cannot find symbol
symbol : class File
location: class ReplaceFirstComment
ReplaceFirstComment(File input, File output) {
^
ReplaceFirstComment.java:2: cannot find symbol
symbol : class File
location: class ReplaceFirstComment
ReplaceFirstComment(File input, File output) {
^
2 errors
----------------------------------------------------

OK so we need to fix those errors ...

----------------------------------------------------
C:\temp>type ReplaceFirstComment.java
import java.io.*;

class ReplaceFirstComment {
ReplaceFirstComment(File input, File output) {
// TODO
}
}

C:\temp>javac ReplaceFirstComment.java
C:\temp>
----------------------------------------------------

It compiles, now to test it, it should do nothing, does it?

----------------------------------------------------
C:\temp>java ReplaceFirstComment.java
Exception in thread "main" java.lang.NoClassDefFoundError:
ReplaceFirstComment/java
Caused by: java.lang.ClassNotFoundException: ReplaceFirstComment.java
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)

C:\temp>
----------------------------------------------------

Oh, we are missing a "main" method. We need to add some sort of test
harness, so I'll deal with both issues the simplest way.

----------------------------------------------------
C:\temp>type ReplaceFirstComment.java
import java.io.*;

class ReplaceFirstComment {

ReplaceFirstComment(File input, File output) {
// TODO
}

public static void main (String[] args) {
File input = new File(args[0]);
File output = new File(args[1]);
new ReplaceFirstComment(input, output);
}

}

C:\temp>javac ReplaceFirstComment.java

C:\temp>java ReplaceFirstComment ReplaceFirstComment.java Replaced.java

C:\temp>
----------------------------------------------------

OK, test sucessful? - your turn.


At this point you may be thinking "Hey RGB, I'm an intermediate Java
programmer and I know all this stuff, it's trivial, why are you wasting
your and my time with it?"

The point is you haven't followed this process else you'd have some
small example code that is more developed than this and shows us where
you got stuck.


So what have you come up with so far?
 
E

ElementX

ElementX said:
ElementX wrote:
On Oct 1, 12:42 pm, RedGrittyBrick <[email protected]>
wrote:
ElementX wrote:
There is two java classes
second class is for execute ant file.
First Class does the most.
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
"<!-- ...
-->"
has any body have an example class to do it?
Thanks a lot...if you can help...I create a class but is not
working...maybe I can post it here...
Do post it here. It would help if you explain *exactly* what you mean by
"is not working".
--
RGB
the following code was wrote for mappings in jar file...maybe can
help...
[code omitted]
If you wrote that then you are skilled enough in Java that you don't
need my help.
If I were tackling the assignment you describe, I would not start with
the code you posted. I'd start from scratch.
Assuming you didn't in fact write the code you posted, you might find
Patricia's guide helpful:http://home.earthlink.net/~patricia_shanahan/beginner.html
I'd start with the requirement "first create a plain class which accepts
two java.io.File object in constructor as input". From this I'd write
     class ReplaceFirstComment {
         ReplaceFirstComment(File input, File output) {
             // TODO
         }
     }
Then I'd compile it and test it. I'd not move on until I was entirely
happy with the test results and had eliminated any compiler warnings.
Then I'd think about the next tiny change that I could make that I could
compile and test.
Do you have an idea...or an example file...which can help more

My idea was you take my starting point (above) and build on it step by step.

Here's how I imagined proceeding ...

----------------------------------------------------
C:\temp>type ReplaceFirstComment.java
class ReplaceFirstComment {
     ReplaceFirstComment(File input, File output) {
         // TODO
     }

}

C:\temp>javac ReplaceFirstComment.java
ReplaceFirstComment.java:2: cannot find symbol
symbol  : class File
location: class ReplaceFirstComment
     ReplaceFirstComment(File input, File output) {
                         ^
ReplaceFirstComment.java:2: cannot find symbol
symbol  : class File
location: class ReplaceFirstComment
     ReplaceFirstComment(File input, File output) {
                                     ^
2 errors
----------------------------------------------------

OK so we need to fix those errors ...

----------------------------------------------------
C:\temp>type ReplaceFirstComment.java
import java.io.*;

class ReplaceFirstComment {
     ReplaceFirstComment(File input, File output) {
         // TODO
     }

}

C:\temp>javac ReplaceFirstComment.java
C:\temp>
----------------------------------------------------

It compiles, now to test it, it should do nothing, does it?

----------------------------------------------------
C:\temp>java ReplaceFirstComment.java
Exception in thread "main" java.lang.NoClassDefFoundError:
ReplaceFirstComment/java
Caused by: java.lang.ClassNotFoundException: ReplaceFirstComment.java
         at java.net.URLClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClassInternal(Unknown Source)

C:\temp>
----------------------------------------------------

Oh, we are missing a "main" method. We need to add some sort of test
harness, so I'll deal with both issues the simplest way.

----------------------------------------------------
C:\temp>type ReplaceFirstComment.java
import java.io.*;

class ReplaceFirstComment {

     ReplaceFirstComment(File input, File output) {
         // TODO
     }

     public static void main (String[] args) {
         File input = new File(args[0]);
         File output = new File(args[1]);
         new ReplaceFirstComment(input, output);
     }

}

C:\temp>javac ReplaceFirstComment.java

C:\temp>java ReplaceFirstComment ReplaceFirstComment.java Replaced.java

C:\temp>
----------------------------------------------------

OK, test sucessful? - your turn.

At this point you may be thinking "Hey RGB, I'm an intermediate Java
programmer and I know all this stuff, it's trivial, why are you wasting
your and my time with it?"

The point is you haven't followed this process else you'd have some
small example code that is more developed than this and shows us where
you got stuck.

So what have you come up with so far?

At first thanks a lot...for your help...
so I create some code...what do yu think...what is the next step...?
Now, I can replace // comments from a text file...how 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();
}
}

// 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;
}



}
 
R

RedGrittyBrick

ElementX said:
RedGrittyBrick said:
ElementX said:
RedGrittyBrick wrote:
ElementX wrote:
RedGrittyBrick wrote:
ElementX wrote:
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
"<!-- ...
-->"
has any body have an example class to do it?
I'd start with the requirement "first create a plain class which accepts
two java.io.File object in constructor as input [and output]" From this
I'd write
class ReplaceFirstComment {
ReplaceFirstComment(File input, File output) {
// TODO
}
}
Then I'd compile it and test it. I'd not move on until I was entirely
happy with the test results and had eliminated any compiler warnings.
Then I'd think about the next tiny change that I could make that I could
compile and test.

At first thanks a lot...for your help...
so I create some code...what do yu think...what is the next step...?
Now, I can replace // comments from a text file...how 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>();

Hmm, your original specification makes no mention of lists of files to
include, lists to exclude and FileSets. Is this something you omitted
from the statement of what you are trying to achieve?

@SuppressWarnings("unused")
private String charset;

Why Suppress warnings about unused variables? I find it better to remove
them.
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) {

Neither of these constructors match the signature you mentioned in your
first post. Why is that?

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", "/*");

I'd cut that out entirely - When I need to keep old versions of code
around I use a Version Control System of some sort.
RemoveHeader rh = new RemoveHeader();
rh.removeCommentFromFile("test.txt", "//");
}

OK, but it doesn't really match the spec.
I'd be awfully tempted to shorten those two lines to
new RemoveHeader().removeCommentFromFile("text.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;
}

None of the above do anything at present. They are clutter. I'd remove
them until I got the core of the program working.
public void removeCommentFromFile(String file, String comment) {

That is insufficient to specify the types of comments you want to
remove. I think instead of "String comment" you need "String
commentStart, String commentEnd".

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.

Your original spec suggested that the class would be constructed passing
the name of an input file and the name of an output file, now you seem
to be doing an in-place edit (using a temporary file and rename,
delete). Why doesn't your code match the requirements description?
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;

Why initialise it to null?
while ((line = br.readLine())!=null) {
if (!line.trim().startsWith(comment)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();

The above is the core of the processing. Now you need to keep track of
the start and end of comments, including those that span multiple lines.

You need to plan how you will deal with nested comments.

I'd construct some test data and use that to think about suitable
control structures. Many people would consider this a language-parsing
problem rather than the simple line-editing problem that your code supposes.

Some example test data I'd think about:

------------testfile1-----------------
Lorem ipsum dolor sit amet, consectetur
/*
adipisicing elit, sed do eiusmod tempor
*/
incididunt ut labore et dolore magna aliqua.

------------testfile2-----------------
Lorem ipsum dolor sit amet, consectetur
adipisicing /* elit, */ sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua.

------------testfile3-----------------
Lorem ipsum dolor sit amet, consectetur
adipisicing /* elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua.
Ut enim ad */ minim veniam, quis nostrud
exercitation ullamco laboris nisi ut

------------testfile4-----------------
Lorem ipsum dolor sit amet, consectetur
adipisicing /* elit, sed do eiusmod tempor
incididunt /* ut labore et dolore magna aliqua.
Ut enim ad minim*/ veniam*/, quis nostrud
exercitation ullamco laboris nisi ut

------------testfile5-----------------
Lorem ipsum dolor sit amet, consectetur
adipisicing /* elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud

------------testfile6-----------------
Lorem ipsum dolor sit amet, consectetur
adipisicing /** elit, sed do eiusmod tempor
* incididunt ut labore et dolore magna aliqua.
Ut enim */ ad minim veniam, quis nostrud


Maybe you need a variable that keeps track of comment/noncomment state
at each point in the file?

Maybe you need to read the whole file as a single string and search for
the positions of the start and end comment markers?

Maybe you do need to deal with nested comments the same way Java, c, etc
compilers do? Perhaps they have different rules?
[remaining code omitted]

I think your 180 lines can be boiled down to this:

-----------------------------------8<------------------------------------
import java.io.*;

public class ReplaceFirstComment {

public static void main(String[] args) {
File inFile = new File("test.txt");
File outFile = new File("out.txt");
new ReplaceFirstComment(inFile, outFile).doit();
}

private File inFile, outFile;

ReplaceFirstComment(File inFile, File outFile) {
this.inFile = inFile;
this.outFile = outFile;
}

private void doit() {
try {
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}

BufferedReader br = new BufferedReader(
new FileReader(inFile));
PrintWriter pw = new PrintWriter(
new FileWriter(outFile));

String comment = chooseCommentMarker(inFile);
String line;

while ((line = br.readLine()) != null) {
if (!line.trim().startsWith(comment)) {
pw.println(line);
pw.flush();
}
}

pw.close();
br.close();

} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}

private String chooseCommentMarker(File file) {
return "//";
}

}
-----------------------------------8<------------------------------------
Untested.

I've removed comments but I would keep (some of) them in real life.

I've also rearranged the constructor signature to match what you
originally stated.

Personally, I find the above a lot more readable. YMMV.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,830
Latest member
ZADIva7383

Latest Threads

Top