Wednesday 8 January 2014

Java : Remove comments from a text file

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ques2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *
 * @author Sunshine
 */
public class RemoveComments {
    void RemoveComments(String inputFilePath, String outputFilePath) throws FileNotFoundException, IOException {
    File in = new File(inputFilePath);
    File out = new File(outputFilePath);
    BufferedReader bufferedreader = new BufferedReader(new FileReader(in));
    PrintWriter pw = new PrintWriter(new FileWriter(out));
    String line = null, lineToRemove = null;
    while ((line = bufferedreader.readLine()) != null) {
        if (line.startsWith("/*") && line.endsWith("*/")) {
            lineToRemove = line;
        }
        if (!line.trim().equals(lineToRemove)) {
            pw.println(line);
            pw.flush();
        }
    }
}
}

No comments:

Post a Comment