2017-03-09 25 views
0

我有一個java代碼,必須每天從URL保存一個圖像。我想把可執行的jar文件放在windows啓動文件夾中,以便每次啓動Windows時以及連接到Internet時運行;但是,窗口可能每天都會啓動一次以上。所以,我想我的代碼檢查是否已經運行並保存了圖像,它不再運行(保存圖像的名稱是壁紙,我不想更改它的名稱)。我怎樣才能做到這一點?謝謝。檢查一天只運行一次,當連接互聯網

public static void main(String[] args) throws Exception { 
    String imageUrl ="http://imgs.yooz.ir/fc/m/medium-news/0170220/656760513-0.jpg"; 

    String destinationFile = "E:\\Picture\\Wallpaper.jpg"; 

    saveImage(imageUrl, destinationFile); 
} 

public static void saveImage(String imageUrl, String destinationFile) throws IOException { 
    URL url = new URL(imageUrl); 

    byte[] b = new byte[2048]; 
    int length; 

    try { 
     InputStream is=url.openStream(); 
      OutputStream os = new FileOutputStream(destinationFile); 
      while ((length = is.read(b)) != -1) { 
       os.write(b, 0, length); 
      } 
      is.close(); 
      os.close(); 
     } 
    }catch (UnknownHostException e){ 
     e.printStackTrace(); 
    } 
} 

回答

0
final long dayMilliSec=24*60*60*1000; 
final long diffMilliSec=(3*60+30)*60*1000; 
File file=new File(location); 
long modDay=(file.lastModified()+diffMilliSec)/dayMilliSec; 
long currDay=(new Date().getTime()+diffMilliSec)/dayMilliSec; 
//int a=(int) Math.ceil(b); 
if (currDay==modDay){ 
    System.exit(0); 
} 
0

只有當前時間大於目標文件上次修改時間後的24小時時,才能下載映像。

+0

thanks httPants。但我是java的初學者;我怎樣才能找到文件的修改時間? –