5

How do I invoke a main() method of one class in another class? I have two classes SaveData and DynamicTest. Both of the classes contain a main() method. I would like to want to run my main in DynamicTest class. How do I properly call SaveData?

public class SaveData {

    private static final Map<String, Object> myCachedTreeMap = new TreeMap<String, Object>();


    public static final List<String> getLines(final String resourceParam, final Charset charset) throws IOException{
        System.out.println("Please get: "+resourceParam);
        if (myCachedTreeMap.containsKey(resourceParam) ) {
            // Use the cached file, to prevent an additional read.
            System.out.println("Found in memory : "+resourceParam);

        }   
        else {
            // Load the file from disk
            System.out.println("Not Found in memory : "+resourceParam);
        }

        return null;


    }


    public static void main(String[] args) throws IOException {
        String target_dir = "C:\\myfiles\\config\\en";
        String output = "C:\\myfiles\\config\\en\\output.txt";
        File dir = new File(target_dir);
        File[] files = dir.listFiles();

        if (files == null || files.length < 1) {
            System.out.println("File list is empty...");
            return;
        }

        // open the Printwriter
        PrintWriter outputStream = new PrintWriter(output);

        try {

            for (File textFile : files) {
                if (textFile.isFile() && textFile.getName().endsWith(".txt")) {
                    readFromDisk(textFile);                 
                }
            }
        }
        finally {
            outputStream.close();
        }
        String fileNameFromCache = "en_synonyms.txt";
        Object Sheet1 = myCachedTreeMap.get(fileNameFromCache);
        System.out.println(fileNameFromCache + " : \n" + Sheet1);
    }

    @SuppressWarnings("resource")
    private static void readFromDisk(File textFile) throws FileNotFoundException, IOException {

        BufferedReader inputStream;
        inputStream = null;
        String content = "";
        try {
            inputStream = new BufferedReader(new FileReader(textFile));
            content = readFile(textFile);
            System.out.println("Bytes Read = "+content.length());
            // Save contents
            FileContentsObject Sheet1 = new FileContentsObject(System.currentTimeMillis(),
                    textFile.lastModified(), content,
                    textFile.getName(),
                    getLines(null, null));
            // add to map
            myCachedTreeMap.put(textFile.getName(), Sheet1);
        }
        finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }


    private static String readFile(File f) throws FileNotFoundException, IOException, UnsupportedEncodingException  {
        StringBuilder text = new StringBuilder(1024);
        int read, N = 1024 * 1024;
        char[] buffer = new char[N];


            BufferedReader br = null;
            try {
                br = new BufferedReader(
                                new InputStreamReader(
                                new FileInputStream(f), "UTF8"));


                while(true) {
                    read = br.read(buffer, 0, N);
                    if (read > 0)
                        text.append(new String(buffer, 0, read));

                    if(read < N) {
                        break;
                    }
                }
            }
            finally {
                if (br != null)
                    br.close();
            }

        return text.toString();
    }   


    private static final class FileContentsObject {
        private long cachedTime; // currentTime
        private long lastModifiedTimestamp;
        private String contents;
        List<String> lines;
        private String fileName;

        public FileContentsObject(long cachedTime, long lastModifiedTimestamp,
                String contents, String fileName, List<String> lines) {
            this.cachedTime = cachedTime;
            this.lastModifiedTimestamp = lastModifiedTimestamp;
            this.contents = contents;
            this.fileName = fileName;
            this.lines = lines;
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy HH:mm:ss");


            System.out.println("Current Time & Date:" + sdf.format(cachedTime));

            System.out.println("Last Modified Time Stamp:"
                    + sdf.format(lastModifiedTimestamp));

        }
        /**
         * 
         * @return The lines from the file
         */
        List<String> getLines() {
            return this.lines;
        }
        public String toString() {
            return "Sheet1{" + "fileName='" + fileName + '\'' + ", contents='"
                    + contents + '\'' + ", lastModifiedTimestamp="
                    + lastModifiedTimestamp + ", CurrentTime&Date="
                    + cachedTime + '}';



        }
    }
}

public class DynamicTest {

    public static void main(String[] args) {
        Charset charset = Charset.forName("UTF-8");



        try {
            List<String> lines = CacheData.getLines("en_synonyms", charset) ;
            if (lines != null) {
                System.out.println("Number of Lines: "+lines.size());
                for (String line:lines) {
                    System.out.println("DynamicTest:: "+line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();



        }



        try {
            List<String> lines = CacheData.getLines("en_stopwords", charset) ;
            if (lines != null) {
                System.out.println("Number of Lines: "+lines.size());
                for (String line:lines) {
                    System.out.println("DynamicTest:: "+line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();



        }


    }

}
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
FullNelson
  • 99
  • 2
  • 13
  • If you don't know how to call static methods, you should read a tutorial. – fabian May 26 '15 at 13:37
  • You can do this, but is not recommended. If you are only gonna call the `main` method of SaveData from DynamicTest, then rename the main to some other method. I also see you haven't used args and so you should have a method without any arguments. – Harsh Poddar May 26 '15 at 13:39

3 Answers3

3

You call it like any other static method call :

SaveData.main (args); // it's up to you whether to pass the same args or
                      // different args
Eran
  • 387,369
  • 54
  • 702
  • 768
  • This, but I suggest not using a big ```main```method. Just define an auxiliar method and call it. Apart, IMO do not declare multiple mains – Manu Artero May 26 '15 at 13:41
  • @manutero can you explain what you mean by "not using a big main method"? – FullNelson May 26 '15 at 13:54
  • @FullNelson change *big* for *long* (sorry); Your main has ~25 lines related with program logic, just **good coding practice**; [From this answer](http://stackoverflow.com/a/7911881/1614677) quote this lines: *main() doesn't really belong with the data and behaviour of our everyday classes, as I doubt that every class needs to be executable on its own. main()'s concern is with running our program.* Apart, [see this question](http://stackoverflow.com/questions/732151/java-main-method-good-coding-style) – Manu Artero May 26 '15 at 14:02
1

In the main method of DynamicTest write this SaveData.main(args);

Static method call :

Class.method();

Non static method call :

Class object = new Class();
object.method();
Soumitri Pattnaik
  • 3,246
  • 4
  • 24
  • 42
0

Main declaration is always static so you must call it like other static methods, in your case:

SaveData.main (args);
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • are there any cons related to having two main methods? What are my options with regard to removing the main from CacheData? – FullNelson May 26 '15 at 18:56