Часто возникает необходимость скачать файл из сети по http или ftp протоколу, эти примеры далеки от совершенства, но вполне рабочие, пользуйтесь.
FTP вариант требует commons.apache.org (http://commons.apache.org/prop... lient.html)
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
| public static void downloadFile(String srcURL, String destPath, int bufferSize) {
InputStream in = null;
OutputStream out = null;
try {
URL url = new URL(srcURL);
URLConnection conn = url.openConnection();
conn.connect();
in = conn.getInputStream();
out = new FileOutputStream(destPath);
byte buffer[] = new byte[bufferSize];
int c = 0;
while ((c = in.read(buffer)) > 0) {
out.write(buffer, 0, c);
}
out.flush();
} catch (IOException e) {
System.out.println("File " + srcURL + " not found at server");
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
}
}
}
static public void downloadFtpCommons(String server, String folder, String file, String destPath) {
FTPClient ftp;
ftp = new FTPClient();
OutputStream output;
try {
ftp.connect(server);
System.out.println("Connected to " + server + " on " + ftp.getDefaultPort());
System.out.println(ftp.getReplyString());
ftp.login("anonymous", "a@z.com");
System.out.println(ftp.getReplyString());
// ftp.enterLocalPassiveMode();
ftp.enterLocalActiveMode();
System.out.println(ftp.getReplyString());
ftp.cwd(folder);
System.out.println(ftp.getReplyString());
// ftp.setFileType(FTP.ASCII_FILE_TYPE);
// System.out.println(ftp.getReplyString());
ftp.enterLocalPassiveMode();
System.out.println(ftp.getReplyString());
output = new FileOutputStream(destPath);
ftp.retrieveFile(file, output);
System.out.println(ftp.getReplyString());
output.close();
ftp.logout();
System.out.println(ftp.getReplyString());
} catch (IOException e) {
e.printStackTrace();
}
} |
|
Очень поверхностное объяснение: различные протоколы  |