簡體   English   中英

While循環在Java中為LogMonitor執行無限次

[英]While loop executing infinite times in java for LogMonitor

我正在一個Java程序記錄對文本文件所做的更改,將其寫入其他日志文件並通過電子郵件發送的項目。 我面臨的問題是用於監視更改的while循環沒有中斷。 如果我在while循環中放入郵寄代碼,則郵件將進入無限循環狀態。 如果我將代碼放在while循環之外,則main無法到達那里,因為while處於無限循環中。 我需要一個休息條件,我無法弄清楚。 有人可以幫忙嗎?

import java.util.Properties;  
import java.io.*;
import javax.mail.*;  
import javax.mail.internet.*;  
import javax.activation.*;  

public class LogMonitor {
    public static void main(String[] args) throws Exception
{
        FileReader fr = new FileReader("D:/test.txt");
        BufferedReader br = new BufferedReader(fr);
        while (true) {
            String line = br.readLine();
            if (line == null)
            {
                Thread.sleep(1*1000);
            } else
            {
                byte[] y = line.getBytes();
                File g = new File("D:/abc.txt");
                try (OutputStream f = new FileOutputStream(g,true))
                {
                    f.write( y );
                }
            }    

 String to="abcde@gmail.com";//change accordingly  
  final String user="vwxyz@gmail.com";//change accordingly  
  final String password="xxxxxxx";//change accordingly  
 // final String d_port  = "465";

  //1) get the session object
  // java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
   Properties props = new Properties();
                props.put("mail.smtp.host", "smtp.gmail.com");
                props.put("mail.smtp.socketFactory.port", "465");
                props.put("mail.smtp.socketFactory.class",
                                "javax.net.ssl.SSLSocketFactory");
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.port", "465");

  Session session = Session.getDefaultInstance(props,  
   new javax.mail.Authenticator()
   {  
   @Override
   protected PasswordAuthentication getPasswordAuthentication()
   {  
   return new PasswordAuthentication(user,password);  
   }  
   });

  //2) compose message    
  try{  
    MimeMessage message = new MimeMessage(session);  
    message.setFrom(new InternetAddress(user));  
    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
    message.setSubject("Message Alert! Changes made to your file");  

    //3) create MimeBodyPart object and set your message text    
    BodyPart messageBodyPart1 = new MimeBodyPart();  
    messageBodyPart1.setText("This is message body");  

    //4) create new MimeBodyPart object and set DataHandler object to this object      
   MimeBodyPart messageBodyPart2 = new MimeBodyPart();  

 String filename = "D://abc.txt";//change accordingly  
    DataSource source = new FileDataSource(filename);  
    messageBodyPart2.setDataHandler(new DataHandler(source));  
   messageBodyPart2.setFileName(filename);  


    //5) create Multipart object and add MimeBodyPart objects to this object      
    Multipart multipart = new MimeMultipart();  
    multipart.addBodyPart(messageBodyPart1);  
   multipart.addBodyPart(messageBodyPart2);  

    //6) set the multiplart object to the message object  
    message.setContent(multipart );  

    //7) send message  
    Transport.send(message);  

   System.out.println("message sent....");  
   }catch (MessagingException ex) {
       System.out.println(ex);


   }  
        }
}}

First Move發送電子郵件ail阻止為單獨的方法。 我只是剪切並粘貼了您的代碼..

public static void sendEmail() {
    String to = "abcde@gmail.com";// change accordingly
    final String user = "vwxyz@gmail.com";// change accordingly
    final String password = "xxxxxxx";// change accordingly
    // final String d_port = "465";

    // 1) get the session object
    // java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, password);
        }
    });

    // 2) compose message
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(user));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject("Message Alert! Changes made to your file");

        // 3) create MimeBodyPart object and set your message text
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setText("This is message body");

        // 4) create new MimeBodyPart object and set DataHandler object to this object
        MimeBodyPart messageBodyPart2 = new MimeBodyPart();

        String filename = "D://abc.txt";// change accordingly
        DataSource source = new FileDataSource(filename);
        messageBodyPart2.setDataHandler(new DataHandler(source));
        messageBodyPart2.setFileName(filename);

        // 5) create Multipart object and add MimeBodyPart objects to this object
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart1);
        multipart.addBodyPart(messageBodyPart2);

        // 6) set the multiplart object to the message object
        message.setContent(multipart);

        // 7) send message
        Transport.send(message);

        System.out.println("message sent....");
    }
    catch (MessagingException ex) {
        System.out.println(ex);

    }

}

然后添加boolean來標記main中的更改。.注意isFileChanged用於向捕獲的更改發送電子郵件。

public static void main(String[] args) throws Exception {
    FileReader fr = new FileReader("D:/test.txt");
    BufferedReader br = new BufferedReader(fr);
    boolean isFileChanged = false;
    while (true) {
        String line = br.readLine();
        if (line == null) {
            if (isFileChanged){
                isFileChanged = false;
                sendEmail();
            }
            Thread.sleep(1 * 1000);
        }
        else {
            isFileChanged = true;
            byte[] y = line.getBytes();
            File g = new File("D:/abc.txt");
            try (OutputStream f = new FileOutputStream(g, true)) {
                f.write(y);
            }
        }

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM