Форум программистов, компьютерный форум, киберфорум
Java: Сети
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.90/29: Рейтинг темы: голосов - 29, средняя оценка - 4.90
92 / 92 / 18
Регистрация: 06.01.2012
Сообщений: 394
1

Commons net ftp file download

13.11.2012, 20:43. Показов 5757. Ответов 18
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Есть код, который делает download файла c ftp.
Для локального фтп всё работает.
Для удалённого сервера(доступ через интернет) ftp.tomsk.ru файл загрузить не получается.
Java
1
2
3
4
OutputStream output;
output = new FileOutputStream(local);
ftp.retrieveFile(remote, output);
output.close();
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
13.11.2012, 20:43
Ответы с готовыми решениями:

Подключение org.apache.commons.net.ftp.FTP
В Java совсем новичок, но есть задача переписать ftp-клиент с C# на Java. Подскажите пожалуйста...

Apache commons net
скачал плагин для сетей отсюда http://commons.apache.org/proper/commons-net/download_net.cgi ...

Apache commons net Ftp в android
Пишу программу для вывода названий файлов и директорий , на java никаких проблем не возникло,...

FTP клиент с использованием org.apache.commons.net
Всем добрый день. Необходимо выгружать фотографии на FTP сервер. Изучив тему полнял что нужно...

18
22 / 22 / 6
Регистрация: 04.08.2011
Сообщений: 103
14.11.2012, 09:05 2
Аналогичная проблема...Полный код класса ниже...подключается но не список файлов, не сами файлы не качает
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
package ru.sanremodv.shop;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
 
import org.apache.commons.net.ftp.FTPClient;
 
public class ftp {
 
    public static String[] getList(String host, String user, String password, String folder){
        
        FTPClient ftp = new FTPClient();
        try{
            ftp.connect(host);
            ftp.login(user, password);
            //if (ftp.isConnected()==true) System.out.println("Connected"); /*Говорит что подключился*/
            
            ftp.changeWorkingDirectory(folder);
            return ftp.listNames();
            
        }catch(IOException e){
            System.out.println("Ошибка в getList(FTPClient)");
            e.printStackTrace();
            
        }finally{
            try{ftp.logout(); ftp.disconnect();}catch(IOException e){e.printStackTrace();}
        }
        
        
    }
    public static void upload(String host, String user, String password, String outFile, String inFile){
        FTPClient ftp = new FTPClient();
        FileInputStream fis = null;
        try{
            ftp.connect(host);
            ftp.login(user, password);
         fis = new FileInputStream(inFile);
            ftp.storeFile(outFile, fis);
            
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            try{ftp.logout();
            ftp.disconnect();
            fis.close();}catch(Exception e) {e.printStackTrace();};
            
        }
    }
    public static void download(String host, String user, String password, String outFile, String inFile){
        FTPClient ftp = new FTPClient();
        FileOutputStream fos = null;
        try{
            ftp.connect(host);
            ftp.login(user, password);
            fos = new FileOutputStream(inFile);
            //ftp.changeWorkingDirectory("http");
            //ftp.changeWorkingDirectory("sanremo");
            //ftp.changeWorkingDirectory("theme");
            //ftp.changeWorkingDirectory("lightbloo");
            //ftp.changeWorkingDirectory("images");
            ftp.retrieveFile(outFile, fos);
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            try{ fos.close();}catch(Exception e){System.out.println("Ошибка закрытия выходного потока");}
            try{ftp.logout();}catch(Exception e){System.out.println("Ошибка ftp.logout");}
            try{ftp.disconnect();}catch(Exception e){System.out.println("Ошибка ftp.disconnect");}
        }
    }
    public static void delete(String host, String user, String password, String outFile){
    FTPClient ftp = new FTPClient();
     try{
    ftp.connect(host);
    ftp.login(user, password);
    ftp.deleteFile(outFile);
    
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            try {ftp.logout();
            ftp.disconnect();} catch(Exception ex){ex.printStackTrace();}
        }
    }
}
0
2586 / 2259 / 257
Регистрация: 14.09.2011
Сообщений: 5,185
Записей в блоге: 18
14.11.2012, 15:47 3
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
    public static void downloadFile(String srcURL, String destPath, int bufferSize) {
        InputStream in = null;
        OutputStream out = null;
        try {
            URL url = new URL(srcURL);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            in = httpConn.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) {
               
            }
        }
    }
0
22 / 22 / 6
Регистрация: 04.08.2011
Сообщений: 103
15.11.2012, 04:27 4
А если фтп не публичный? тогда таким способом ведь не залить и не скачать

Добавлено через 25 минут
Эм, хотя если в урл написать userass@host то наверно сработает..спасибо

Добавлено через 2 часа 12 минут
Все же открытым остается вопрос почему не вышло сделать через apache common ?
0
92 / 92 / 18
Регистрация: 06.01.2012
Сообщений: 394
15.11.2012, 08:22  [ТС] 5
alekola,
Java
1
2
3
4
5
6
7
8
        ftp.enterLocalPassiveMode();
        try {
        System.out.println(ftp.printWorkingDirectory());//Рабочая дирректория
        FTPFile[] fls=ftp.listFiles();
        for (FTPFile f : fls) {
                    System.out.println(f.getName()+(f.isDirectory()?"/":""));
                }
        }catch(IOException e){e.printStackTrace();};
Вообще натыкался на JavaTalks там побитово картинки считывают. М.б стоит попробовать. А вообще совершенно нет идей чего с commons-net не так. Скорее всего какую нибудь опцию не указали при подключении/скачке, режим не включили. Нормальных мануалов по библиотеке нет же. Только в инете сёрфить.

Добавлено через 31 минуту
Да, кстати по поводу неработающего listFiles(), мне лично помогло отключение брандмауера.
0
22 / 22 / 6
Регистрация: 04.08.2011
Сообщений: 103
15.11.2012, 11:40 6
Я на linux opensuse сижу, с бренмауром все в порядке вроде. Весь день копал сегодня но пишу сейчас с мобилы. Доберусь до компа расскажу что узнал

Добавлено через 24 минуты
Вообщем ситуация такая.
Успешные операции
ftp.connect
ftp.login
Статус состояние - все вери велл.
listFiles && retrieveFile дают null
Открыл исходник retrieveFile
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
protected boolean _retrieveFile(String command, String remote, OutputStream local)
1673        throws IOException
1674        {
1675            Socket socket;
1676    
1677            if ((socket = _openDataConnection_(command, remote)) == null) {
1678                return false;
1679            }
1680    
1681            InputStream input = new BufferedInputStream(socket.getInputStream(),
1682                    getBufferSize());
1683            if (__fileType == ASCII_FILE_TYPE) {
1684                input = new FromNetASCIIInputStream(input);
1685            }
1686    
1687            CSL csl = null;
1688            if (__controlKeepAliveTimeout > 0) {
1689                csl = new CSL(this, __controlKeepAliveTimeout, __controlKeepAliveReplyTimeout);
1690            }
1691    
1692            // Treat everything else as binary for now
1693            try
1694            {
1695                Util.copyStream(input, local, getBufferSize(),
1696                        CopyStreamEvent.UNKNOWN_STREAM_SIZE, __mergeListeners(csl),
1697                        false);
1698            } finally {
1699                Util.closeQuietly(socket);
1700            }
1701    
1702            if (csl != null) {
1703                csl.cleanUp(); // fetch any outstanding keepalive replies
1704            }
1705            // Get the transfer response
1706            boolean ok = completePendingCommand();
1707            return ok;
1708        }
Видно что false метод возвращает в 1 случае _openDataConnection_(command, remote)) == null
Когда метод openDataConnection дает null
Открыл исходник метода _openDataConnection_(command, remote)
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
protected Socket _openDataConnection_(String command, String arg)
679        throws IOException
680        {
681            if (__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE &&
682                    __dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE) {
683                return null;
684            }
685    
686            final boolean isInet6Address = getRemoteAddress() instanceof Inet6Address;
687    
688            Socket socket;
689    
690            if (__dataConnectionMode == ACTIVE_LOCAL_DATA_CONNECTION_MODE)
691            {
692                // if no activePortRange was set (correctly) -> getActivePort() = 0
693                // -> new ServerSocket(0) -> bind to any free local port
694                ServerSocket server = _serverSocketFactory_.createServerSocket(getActivePort(), 1, getHostAddress());
695    
696                try {
697                    // Try EPRT only if remote server is over IPv6, if not use PORT,
698                    // because EPRT has no advantage over PORT on IPv4.
699                    // It could even have the disadvantage,
700                    // that EPRT will make the data connection fail, because
701                    // today's intelligent NAT Firewalls are able to
702                    // substitute IP addresses in the PORT command,
703                    // but might not be able to recognize the EPRT command.
704                    if (isInet6Address) {
705                        if (!FTPReply.isPositiveCompletion(eprt(getReportHostAddress(), server.getLocalPort()))) {
706                            return null;
707                        }
708                    } else {
709                        if (!FTPReply.isPositiveCompletion(port(getReportHostAddress(), server.getLocalPort()))) {
710                            return null;
711                        }
712                    }
713        
714                    if ((__restartOffset > 0) && !restart(__restartOffset)) {
715                        return null;
716                    }
717    
718                    if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
719                        return null;
720                    }
721    
722                    // For now, let's just use the data timeout value for waiting for
723                    // the data connection.  It may be desirable to let this be a
724                    // separately configurable value.  In any case, we really want
725                    // to allow preventing the accept from blocking indefinitely.
726                    if (__dataTimeout >= 0) {
727                        server.setSoTimeout(__dataTimeout);
728                    }
729                    socket = server.accept();
730                } finally {
731                    server.close();
732                }
733            }
734            else
735            { // We must be in PASSIVE_LOCAL_DATA_CONNECTION_MODE
736    
737                // Try EPSV command first on IPv6 - and IPv4 if enabled.
738                // When using IPv4 with NAT it has the advantage
739                // to work with more rare configurations.
740                // E.g. if FTP server has a static PASV address (external network)
741                // and the client is coming from another internal network.
742                // In that case the data connection after PASV command would fail,
743                // while EPSV would make the client succeed by taking just the port.
744                boolean attemptEPSV = isUseEPSVwithIPv4() || isInet6Address;
745                if (attemptEPSV && epsv() == FTPReply.ENTERING_EPSV_MODE)
746                {
747                    _parseExtendedPassiveModeReply(_replyLines.get(0));
748                }
749                else
750                {
751                    if (isInet6Address) {
752                        return null; // Must use EPSV for IPV6
753                    }
754                    // If EPSV failed on IPV4, revert to PASV
755                    if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) {
756                        return null;
757                    }
758                    _parsePassiveModeReply(_replyLines.get(0));
759                }
760    
761                socket = _socketFactory_.createSocket();
762                socket.connect(new InetSocketAddress(__passiveHost, __passivePort), connectTimeout);
763                if ((__restartOffset > 0) && !restart(__restartOffset))
764                {
765                    socket.close();
766                    return null;
767                }
768    
769                if (!FTPReply.isPositivePreliminary(sendCommand(command, arg)))
770                {
771                    socket.close();
772                    return null;
773                }
774            }
775    
776            if (__remoteVerificationEnabled && !verifyRemote(socket))
777            {
778                socket.close();
779    
780                throw new IOException(
781                        "Host attempting data connection " + socket.getInetAddress().getHostAddress() +
782                        " is not same as server " + getRemoteAddress().getHostAddress());
783            }
784    
785            if (__dataTimeout >= 0) {
786                socket.setSoTimeout(__dataTimeout);
787            }
788    
789            return socket;
790        }
Не успел его до конца досмотреть но null может возвращать если не указан режим передачи
if (__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE &&
682 __dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE) {
683 return null;

Завтра на работе погляжу отпишусь..любой помощи буду рад
0
2586 / 2259 / 257
Регистрация: 14.09.2011
Сообщений: 5,185
Записей в блоге: 18
15.11.2012, 12:52 7
вспомните что в ftp протоколе есть 2 режима работы active и passive, оба по разным портам работают, лист директори - это режим актив, скорее всего он не работает, причин может быть несколько, нужен дебаг пошаговый чтобы выявить, возможно просто сервер не хочет в активе работать по админскому повелению
0
2000 / 1427 / 92
Регистрация: 25.11.2010
Сообщений: 3,611
15.11.2012, 14:02 8
Цитата Сообщение от mutagen Посмотреть сообщение
вспомните что в ftp протоколе есть 2 режима работы active и passive, оба по разным портам работают, лист директори - это режим актив,
Тут есть хитрость, насколько я понимаю. Да, LIST посылает данные в пассивный DTP (This command causes a list to be sent from the server to the passive DTP). Но для клиента по умолчанию пассивный порт тот же, что и для control connection, если судить по спецификации (The user-process default data port is the same as the control connection port, RFC959, section 3.2). Т.е. судя по всему данные отправляются через CC. Иначе я лично не могу объяснить, что я, сидя за прокси в пассивном режиме, получаю листинг директорий.
0
2586 / 2259 / 257
Регистрация: 14.09.2011
Сообщений: 5,185
Записей в блоге: 18
15.11.2012, 14:22 9
Цитата Сообщение от Skipy Посмотреть сообщение
Иначе я лично не могу объяснить, что я, сидя за прокси в пассивном режиме, получаю листинг директорий.
если Вы получаете от лист апача, то у него есть такой пассивный режим, но его можно запретить, возможно и других так же
0
92 / 92 / 18
Регистрация: 06.01.2012
Сообщений: 394
15.11.2012, 17:00  [ТС] 10
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
        FTPClient client = new FTPClient();
             try {
                client.connect("ftp.tomsk.ru");
                    client.login("anonymous", "");
                    client.changeWorkingDirectory("pub");
                client.enterLocalPassiveMode();
                
            FTPFile[] ftpFiles = client.listFiles();
               // for (FTPFile ftpFile : ftpFiles) {
                    ByteArrayOutputStream byteArrayOutputStream = null;
                ByteArrayInputStream byteArrayInputStream = null;
                    try {
                    byteArrayOutputStream = new ByteArrayOutputStream();
                      client.setFileType(FTP.BINARY_FILE_TYPE);
                        client.setFileStructure(FTP.FILE_STRUCTURE);
                    client.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE);
                        System.out.println(client.retrieveFile("m2.zip",byteArrayOutputStream));
                        byteArrayOutputStream.flush();
                    byte[] bArray = byteArrayOutputStream.toByteArray();
                                   System.out.println("CHEK");
                               System.out.println(bArray.toString());
                                   System.out.println(bArray.length);                       
                    }
                    finally {
                        if (byteArrayOutputStream != null)
                            byteArrayOutputStream.close();
                        if (byteArrayInputStream != null)
                            byteArrayInputStream.close();
                    }
               // }
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                try {
                    client.disconnect();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
в output говорится, что в byteArray содержится 12920 бита, если его можно считать, как картинку, то почему нельзя считать, как файл .

Добавлено через 34 минуты
Вообще мои мыслишки говорят о том, что хотелось бы увидеть ответ сервера на запросы, которые ему посылает FTPClient, но пока нету времени в это залезть.
0
2586 / 2259 / 257
Регистрация: 14.09.2011
Сообщений: 5,185
Записей в блоге: 18
15.11.2012, 18:50 11
Цитата Сообщение от RequiemMass Посмотреть сообщение
если его можно считать, как картинку, то почему нельзя считать, как файл .
может дело в mime encoding?
0
92 / 92 / 18
Регистрация: 06.01.2012
Сообщений: 394
15.11.2012, 19:15  [ТС] 12
Цитата Сообщение от mutagen Посмотреть сообщение
mime encoding
Можно поподробнее? Гугл говорит, что речь идёт почтовом формате, что вы имеете ввиду?
0
2586 / 2259 / 257
Регистрация: 14.09.2011
Сообщений: 5,185
Записей в блоге: 18
15.11.2012, 20:29 13
http://en.wikipedia.org/wiki/Internet_media_type
0
92 / 92 / 18
Регистрация: 06.01.2012
Сообщений: 394
16.11.2012, 22:50  [ТС] 14
Цитата Сообщение от mutagen Посмотреть сообщение
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
Java
1
downloadFile("ftp://anonymous@ftp.tomsk.ru/pub/FAQ/","D:/out/uucpgaq.txt",Integer.MAX_VALUE);
ftp.FtpURLConnection cannot be cast to java.net.HttpURLConnection
0
2586 / 2259 / 257
Регистрация: 14.09.2011
Сообщений: 5,185
Записей в блоге: 18
17.11.2012, 01:27 15
вот рабочий вариант

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
package net;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
 
public class PullDown {
 
    public static void main(String[] args) {
        String src = "ftp://ftp.tomsk.ru/pub/FAQ/uucpfaq.txt";
        String dest = "uucpfaq.txt";
        downloadFile(src, dest, 1024);
    }
 
    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) {
 
            }
        }
    }
 
}
2
22 / 22 / 6
Регистрация: 04.08.2011
Сообщений: 103
18.11.2012, 05:42 16
это не используя apache commons.
Если кому нужно могу еще привести рабочих вариантов без этой библиотеки
0
92 / 92 / 18
Регистрация: 06.01.2012
Сообщений: 394
18.11.2012, 12:45  [ТС] 17
alekola, я если честно использовал такой, но для меня совершенно загадка почему commons-net отказывается загружать файл. К слову я пробовал использовать commons-net 1.4, результат остался прежним. Я вообще в шоке, сначала у меня получалось хотя бы считать файл, как массив байтов, но когда я писал его на диск он отказывался открываться. Потом, я что то поменял в коде и он перестал загружать у меня файлы, как массив байтов. Бред какой то))))
0
2586 / 2259 / 257
Регистрация: 14.09.2011
Сообщений: 5,185
Записей в блоге: 18
19.11.2012, 11:37 18
Цитата Сообщение от RequiemMass Посмотреть сообщение
но для меня совершенно загадка почему commons-net отказывается загружать файл
видимо не хватило терпения разобраться

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
package net;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
 
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
 
public class PullDown {
 
    public static void main(String[] args) {
        String src = "ftp://ftp.tomsk.ru/pub/FAQ/uucpfaq.txt";
        String dest = "uucpfaq.txt";
        // downloadFile(src, dest, 1024);
 
        String srv = "ftp.ncsa.uiuc.edu";
        String file = "Brochure";
        downloadFtpCommons(srv, "/", file, file);
    }
 
    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();
        }
    }
 
}
2
92 / 92 / 18
Регистрация: 06.01.2012
Сообщений: 394
19.11.2012, 12:46  [ТС] 19
Java
1
2
3
4
downloadFtpCommons("ftp.tomsk.ru","pub","m2.zip","D:/out/m2.zip");
/*зип файл поверёждён и не открывается, метод с URL загружал его нормально. Там абракадабра, но всё же открывается.*/
downloadFtpCommons("ftp.tomsk.ru","pub/FAQ","uucpfaq.txt","D:/out/uucpfaq.txt");
/* Текст файл копирует нормально */
Вы меня даже расстроили, знали бы сколько я мучился и потратил времени. Не работает и всё и во всех примерах одно и тоже пишут, а я пишу как в примерах и у меня не работает. (:
Просто фишка в том, что это метод в программе, которая позволяет выполнять коннект логин, всё разными методами. Благодаря тому, что он 100% работает я сейчас смогу определить, почему раньше не работал.

Добавлено через 18 минут
mutagen, Хотя еслиб не вы наверно ещё бы столько же времени потратил, поэтому большое спасибо )
0
19.11.2012, 12:46
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
19.11.2012, 12:46
Помогаю со студенческими работами здесь

File Download
Есть форма, на форме поле "Pict" типа Richtext Есть xpage с 2мя полями(Controls) - "File Upload" и...

WinInet Download File
Нужна небольшая помощь, как этот кусок кода отвязать от консольного приложения к нормальной...

контрол File Download
как в данный контрол отобразить аттачи из другой базы? все другие поля документа чужой базы...

Download file from Google Drive
Проблема состоит в следующем: необходимо используя Google Drive API загрузить файл на устройство...

Download file asp ajax
Добрый вечер, подскажите пожалуйста, вызываю метод через ajax который возвращает файл, return...

Ruby on Rails Paperclip Mongoid file download
Добрый день! Кто может покажите пример кода Ruby on Rails как download file с базы данных Mongoid с...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
19
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru