Bonsoir tout le monde,
J’ai besoin d’accéder à un serveur distant pour télécharger un fichier (.doc)
J’ai trouvé un exemple sur net pour mais ce n’est pas pour le type de fichier que j’ai (.doc).
Encore, je ne sais pas si c’est un code complet
Voici le code
Merci
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 public class MainClass { public static void main(String args[]) throws Exception { URL u = new URL("http://www.java2s.com/binary.dat"); URLConnection uc = u.openConnection(); String contentType = uc.getContentType(); int contentLength = uc.getContentLength(); if (contentType.startsWith("text/") || contentLength == -1) { throw new IOException("This is not a binary file."); } InputStream raw = uc.getInputStream(); InputStream in = new BufferedInputStream(raw); byte[] data = new byte[contentLength]; int bytesRead = 0; int offset = 0; while (offset < contentLength) { bytesRead = in.read(data, offset, data.length - offset); if (bytesRead == -1) break; offset += bytesRead; } in.close(); if (offset != contentLength) { throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes"); } String filenameComplet = u.getFile(); String filename = u.getFile().substring(filenameComplet.lastIndexOf('/') + 1); FileOutputStream out = new FileOutputStream(filename); out.write(data); out.flush(); out.close(); } }
Partager