2015-05-26 25 views
5

Làm cách nào để gọi phương thức main() của một lớp học trong một lớp khác? Tôi có hai lớp học SaveDataDynamicTest. Cả hai lớp đều chứa phương thức main(). Tôi muốn chạy chương trình chính của mình ở lớp DynamicTest. Làm thế nào để tôi gọi đúng số SaveData?Làm cách nào để gọi phương thức main() của một lớp trong một lớp khác?

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(); 



     } 


    } 

} 
+0

Nếu bạn không biết làm thế nào để gọi các phương pháp tĩnh, bạn nên đọc một hướng dẫn. – fabian

+0

Bạn có thể làm điều này, nhưng không được khuyến khích. Nếu bạn chỉ gọi phương thức 'main' của SaveData từ DynamicTest, hãy đổi tên chính thành phương thức khác. Tôi cũng thấy bạn đã không sử dụng args và vì vậy bạn nên có một phương pháp mà không có bất kỳ đối số. –

Trả lời

3

Bạn gọi nó là giống như bất kỳ phương pháp gọi tĩnh khác:

SaveData.main (args); // it's up to you whether to pass the same args or 
         // different args 
+0

Điều này, nhưng tôi đề nghị không sử dụng một '' 'main'''method lớn. Chỉ cần xác định một phương thức quen thuộc và gọi nó. Ngoài ra, IMO không khai báo nhiều nguồn chính – Manu

+0

@manutero bạn có thể giải thích ý của bạn bằng cách "không sử dụng phương pháp chính lớn" không? – FullNelson

+0

@FullNelson thay đổi * lớn * cho * long * (xin lỗi); Chính của bạn có ~ 25 dòng liên quan đến logic chương trình, chỉ ** thực hành mã hóa tốt **; [Từ câu trả lời này] (http://stackoverflow.com/a/7911881/1614677) trích dẫn dòng này: * main() không thực sự thuộc về dữ liệu và hành vi của các lớp học hàng ngày của chúng tôi, như tôi nghi ngờ rằng mọi lớp đều cần có thể thực thi được. Mối quan tâm chính() là chạy chương trình của chúng tôi. * Ngoài ra, [xem câu hỏi này] (http://stackoverflow.com/questions/732151/java-main-method-good-coding-style) – Manu

1

Trong phương pháp chính của DynamicTest viết này SaveData.main(args);

tĩnh gọi phương thức:

Class.method(); 

Non tĩnh gọi phương thức:

Class object = new Class(); 
object.method(); 
0

Main declaration luôn là static vì vậy bạn phải gọi nó như static phương pháp khác, trong trường hợp của bạn:

SaveData.main (args); 
+0

có bất kỳ nhược điểm nào không liên quan đến việc có hai phương pháp chính? Các tùy chọn của tôi liên quan đến việc xóa chính từ CacheData là gì? – FullNelson

Các vấn đề liên quan