2013-07-22 3 views
0

URL이있는 원격 서버에 파일이있는 경우 Java를 어떻게 체크 인 할 수 있습니까? 그럴 경우 파일을 다운로드하십시오.URL이있는 원격 서버에 파일이 있는지 확인하십시오.

다음은 내 코드 샘플입니다. 지정한 URL을 연 다음 URL에서 지정한 파일을 복사 할 I/O 스트림을 만듭니다. 그러나 마침내 그것은 그것이하기로되어있는 것처럼 작동하지 않습니다.

URL url = new URL(" //Here is my URL");  
url.openConnection();  
InputStream reader = url.openStream();  
FileOutputStream writer = new FileOutputStream("t");  
byte[] buffer = new byte[153600];  
int bytesRead = 0;  
while ((bytesRead = reader.read(buffer)) > 0)  
{  
    writer.write(buffer, 0, bytesRead);  
    buffer = new byte[153600];  
}  
writer.close();  
reader.close(); 
+1

404에 대해 오류가 발견되지 않았습니다. –

+0

HTTP의 경우 파일을 찾을 수 없으면 404 응답이 표시됩니다. – Vicky

+1

'buffer'는 while 루프 내부에서 재 할당 할 필요가 없습니다. –

답변

2

이것은

public static boolean exists(String URLName){ 
    try { 
     HttpURLConnection.setFollowRedirects(false); 
     // note : you may also need 
     //  HttpURLConnection.setInstanceFollowRedirects(false) 
     HttpURLConnection con = 
     (HttpURLConnection) new URL(URLName).openConnection(); 
     con.setRequestMethod("HEAD"); 
     return (con.getResponseCode() == HttpURLConnection.HTTP_OK); 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
     return false; 
    } 
    } 
1

파일에 존재하지 않는지 확인하기 위해 서버에 HEAD 요청을 보내기 할 것입니다.

import java.net.*; 
import java.io.*; 

    public static boolean fileExists(String URL){ 
    try { 
     HttpURLConnection.setFollowRedirects(false); 
     HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection(); 
     con.setRequestMethod("HEAD"); 
     if(con.getResponseCode() == HttpURLConnection.HTTP_OK) 
      return true; 
     else 
      return false; 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
     return false; 
     } 
    } 
0

파일이 없으면 url.openConnection()이 FileNotFoundException을 발생시킵니다. 그 이외의 귀하의 코드를 좋아 보인다, 내보기 BufferedInputStream/BufferedOuputStream 및 읽기/쓰기 바이트 사용하여 그것을 청소기 만들 것입니다.

관련 문제