Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.*;

import java.util.Iterator;

import java.util.SortedSet;

public class Main {
    public static int removeUnusedLines(String filename, SortedSet<Integer> linesSet) {

        try {
            BufferedReader br = new BufferedReader(new FileReader(filename));
            //String buffer to store contents of the file
            StringBuffer sb = new StringBuffer("");

            int lineNumber = 1;
            String line;
            Iterator iterator = linesSet.iterator();
            int lineNumberToBeDeleted = (int) iterator.next();

            int count = 0;

            while ((line = br.readLine()) != null) {
                if (lineNumber == lineNumberToBeDeleted) {
                    if (iterator.hasNext()) {
                        lineNumberToBeDeleted = (int) iterator.next();
                        count++;
                    }
                }

                else {
                    sb.append(line + "\n");
                }

                lineNumber++;
            }

            FileWriter fw = new FileWriter(new File(filename));
            //Write entire string buffer into the file
            fw.write(sb.toString());
            fw.close();

            System.err.println("deleted lines" + count);

        } catch (Exception e) {
            System.err.println("error:" + e.getMessage());
            e.printStackTrace();
            return -10;

        }

        return 10;

    }
}