1. 클라이언트 코드를 다운로드하십시오
패키지 javadownload; import java.io.BytearRayoutputStream; import java.io.file; import java.io.fileoutputStream; import java.io.inputstream; import java.net.httpurlConnection; import java.net.url; /** * @description 내보내기 가상 머신 * @author wxt * @version 1.0 * @since */public class getvm {/** * test * @param args */public static void main (string [] args) {String url = "http://192.168.5.102:8845/xx"; 바이트 [] btimg = getVmfromnetByUrl (url); if (null! = btimg && btimg.length> 0) {system.out.println ( "읽기 :" + btimg.length + "byte"); 문자열 filename = "ygserver"; WriteImagetodisk (btimg, filename); } else {System.out.println ( "이 연결에서 얻은 내용 없음"); }}/*** 디스크에 vm을 쓰십시오* @param vm data Stream* @param filename 저장시*/public static void writeimagetodisk (byte [] vm, string filename) {try {file file = 새 파일 ( "./" + filename); fileoutputStream fops = 새 FileOutputStream (file); fops.write (vm); fops.flush (); fops.close (); System.out.println ( "완료 다운로드"); } catch (예외 e) {e.printstacktrace (); }} / *** 주소에서 데이터 가져옵니다* @param strurl 네트워크 연결 주소* @return* / public static byte [] getVmfromnetByUrl (String Strurl) {try {url url = new url (strurl); httpurlconnection conn = (httpurlConnection) url.openConnection (); Conn.setRequestMethod ( "get"); Conn.setConnectTimeout (5 * 1000); inputStream instream = conn.getInputStream (); // 입력 스트림 바이트 [] btimg = readInputStream (instream)을 통해 데이터 가져옵니다. } catch (예외 e) {e.printstacktrace (); } return null; } / *** 입력 스트림에서 데이터를 가져옵니다* @param instream input stream* @return* @throws 예외* / public static byte [] readInputStream (inputStream instream) 예외 {bytearRayoutputStream Outstream = new BytearRayoutputStream (); 바이트 [] 버퍼 = 새로운 바이트 [1024]; int len = 0; while ((len = instream.read (buffer))! = -1) {outstream.write (buffer, 0, len); } instream.close (); Outstream.tobytearray ()를 반환합니다. }}위의 코드는 작은 파일을 다운로드하는 데만 적합합니다. 큰 파일을 다운로드하면 스레드 "Main"Java.lang.outofMemoryError : Java Heap Space 오류에서 예외를 다운로드하면 큰 파일을 다운로드 할 때 위 코드를 수정 해야하는 경우 코드는 다음과 같습니다.
패키지 javadownload; import java.io.BytearRayoutputStream; import java.io.file; import java.io.fileoutputStream; import java.io.inputstream; import java.net.httpurlConnection; import java.net.url; /** * @Description Export Virtual Machine * @Author WXT * @version 1.0 * @since */public class getBigfile {/** * test * @param args */public static void main (string [] args) {String url = "http://192.168.5.76:8080/export/export=123"; 문자열 filename = "yserver"; getVmfromnetByUrl (url, filename); } / *** 주소를 기반으로 파일 다운로드* @param strurl 네트워크 연결 주소* @param filename 다운로드 파일* / public static void getVmfromnetByUrl (String Strurl, String Filename) {try {url url = new url (strurl); httpurlconnection conn = (httpurlConnection) url.openConnection (); Conn.setRequestMethod ( "get"); Conn.setConnectTimeout (5 * 1000); inputStream instream = conn.getInputStream (); // 입력 스트림 바이트를 통해 데이터 가져옵니다 [] 버퍼 = 새 바이트 [4096]; int len = 0; 파일 = 새 파일 ( "./" + filename); fileoutputStream fops = 새 FileOutputStream (file); while ((len = instream.read (buffer))! = -1) {fops.write (buffer, 0, len); } fops.flush (); fops.close (); } catch (예외 e) {e.printstacktrace (); }}}2. 파일 클라이언트 업로드 :
패키지 javadownload; import java.io.datainputstream; import java.io.dataOutputStream; import java.io.file; import java.io.fileInputStream; import java.io.ioexception; import java.io.outputStream; import java.net.httpurlConnection; import java.net.url; 공개 클래스 FileUpload { / ** * 보내기 요청 * * @param url * 요청 주소 * @param filepath * 파일은 서버에 저장되어 있습니다 (여기서는 테스트의 편의성을 위해 작성 될 수 있습니다.이 매개 변수를 제거 할 수 있습니다) * @return * @throws ioexception * / public int (String URL, String Filepath) {filepath); if (! file.exists () ||! file.isfile ()) {return -1; } / *** Part 1* / url urlobj = new URL (url); httpurlconnection con = (httpurlConnection) urlobj.openConnection (); / ** * 키 값 설정 */ con.setRequestMethod ( "post"); // 포스트 모드에서 양식을 제출, 기본값 get 메소드 con.setdoinput (true); con.setdooutput (true); con.setUecaches (false); // Post Mode를 사용할 수 없습니다. // 요청 헤더 정보 Con.setRequestProperty ( "Connection", "Close"); // COP-ALIVE CON.SetRequestProperty ( "charset", "utf-8"); // set boundary string boundary = "-----------" + System.CurrentTimeMillis (); Con.setRequestProperty ( "Content-Type", "multipart/form-data; boundary =" + boundary); // 신체 정보 요청 // 1 부 : StringBuilder sb = new StringBuilder (); sb.append ( "-"); // /////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////Content-Disposition: form-data; name =/"file_name/; filename =/" " + file.getname () +"/"/"/r/n "); sb.tostring (). "UTF-8"; (bytes = in.Read (bufferout)! = -1) {bufferout, 0, bytes); out.close ();/*** 서버 응답을 읽으십시오. 그렇지 않으면 제출이 성공하지 못합니다*/return con.getResponsecode (); con.getinputStream ()). // while; void main (string [] args)은 ioexception {up.send ( "http://192.168.5.102:8845/xx");요약
위의 것은 파일 클라이언트를 다운로드하고 편집기가 소개 한 Java에서 파일 클라이언트를 업로드하기위한 예제 코드입니다. 모든 사람에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 모든 사람에게 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!