powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / Скачать файл с сервера.
3 сообщений из 3, страница 1 из 1
Скачать файл с сервера.
    #37822774
rezor
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Есть сокентое соединение между клиентом и сервером.Сервер предоставляет список файлов. Как лучше скачать выбраный фаил с сервера???Файлы различного типа и размера.
...
Рейтинг: 0 / 0
Скачать файл с сервера.
    #37822776
rezor
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Пробую так:
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
public class FileDownload extends Thread{
	private int readBytes=0;
	private boolean doStop=false;
	//String serverIP,String serverPort,String fileNameLoad,
	 public void run() {
		try {
			URL url = new URL("http://192.168.1.3:7060/home/stas/thread.txt");
			
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.connect();
			BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
			File f1 = new File("MyDownLoad.txt");
			FileOutputStream fw = new FileOutputStream(f1);
			
			byte[] btBuffer = new byte[1024];
			int intRead = 0;
			  while((intRead=bis.read(btBuffer))!= -1){
		           fw.write(btBuffer, 0, intRead);
		           readBytes=readBytes+intRead;
		    }
			  fw.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
	}

}



Получаю exception сервер уже закрыл соединение
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
java.net.SocketException: Connection reset
	at java.net.SocketInputStream.read(SocketInputStream.java:185)
	at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
	at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
	at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
	at java.io.FilterInputStream.read(FilterInputStream.java:133)
	at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:2582)
	at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
	at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
	at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
	at java.io.FilterInputStream.read(FilterInputStream.java:107)
	at FileDownload.run(FileDownload.java:25)


Если не закрывать соединение то в фаил читается все тот же список файлов на сереве.
...
Рейтинг: 0 / 0
Скачать файл с сервера.
    #37823551
Фотография ivanov-void
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
rezor,

См. http://www.jamesholmes.com/TheArtOfJava/] "The Art Of Java" by Herbert Schildt, James Holmes. Там описана реализация полнофункционального менеджера загрузок.

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
...
class Download extends Observable implements Runnable {
	  private static final int MAX_BUFFER_SIZE = 1024;
	
	  public static final int DOWNLOADING = 0;
	  public static final int COMPLETE = 1;
	
	  private URL url; 
	  private int size; 
	  private int downloaded; 
	  private int status; 
	  /**
	   * 
	   * @param url
	   */
	  public Download(URL url) {
		this.url = url;
		size = -1;
		downloaded = 0;
		status = DOWNLOADING;
		
		download();
	  }
	  /**
	   * 
	   */
	  private void download() {
	    Thread thread = new Thread(this);
	    thread.start();
	  }
	  /**
	   * 
	   * @param url
	   * @return
	   */
	  private String getFileName(URL url) {
	    String fileName = url.getFile();
	    return fileName.substring(fileName.lastIndexOf('/') + 1);
	  }
	  /**
	   * 
	   */
	  public void run() {
	    RandomAccessFile file = null;
	    InputStream stream = null;
	
	    try {
	      HttpURLConnection connection =
	        (HttpURLConnection) url.openConnection();
	      connection.setRequestProperty("Range",
	    downloaded + "-");
	
	  connection.connect();
	
	  if (connection.getResponseCode() / 100 != 2) {
	    //error();
	  }
	
	  int contentLength = connection.getContentLength();
	  if (contentLength < 1) {
	    //error();
	  }
	
	  if (size == -1) {
	    size = contentLength;
	    stateChanged();
	  }
	
	  file = new RandomAccessFile(getFileName(url), "rw");
	  file.seek(downloaded);
	
	  stream = connection.getInputStream();
	  while (status == DOWNLOADING) {
	    byte buffer[];
	    if (size - downloaded > MAX_BUFFER_SIZE) {
	      buffer = new byte[MAX_BUFFER_SIZE];
	    } else {
	      buffer = new byte[size - downloaded];
	    }
	
	    int read = stream.read(buffer);
	    if (read == -1)
	      break;
	
	    file.write(buffer, 0, read);
	    downloaded += read;
	    stateChanged();
	  }
	
	  if(status == DOWNLOADING) {
	    status = COMPLETE;
	    stateChanged();
	  }
	} catch(Exception e) {
	  //error();
	} finally {
	  if (file != null) 
	    try {
	      file.close();
	    } catch (Exception e) {
	    	// ...
	    }      
	
	  if (stream != null) 
	    try {
	      stream.close();
	    } catch (Exception e) {
	    	// ...
	        }      
	    }
	  }
	
	  // Notify observers that this download's status has changed.
	  private void stateChanged() {
	    // ...
	  }
}
...
...
Рейтинг: 0 / 0
3 сообщений из 3, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Скачать файл с сервера.
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]