Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can I download file from ftp without save it my directory first

Tags:

java

spring

ftp

I have a page download, where the file you want to download must be downloaded first from other server use ftp. i use this code to download from ftp:

ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

String remoteFile1 = "/Users/A/file.txt";
File downloadFile1 = new File("/Users/B/Downloads/file.txt");
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
outputStream1.close();

if i use this program, i need to save file.txt in my directory /Users/B/Downloads/ then i need to use my other code to download file.txt from /Users/B/Downloads/.

is it possible if i download the file.txt without save it first in my directory /Users/B/Downloads/?

like image 781
viduka Avatar asked Jan 13 '16 09:01

viduka


2 Answers

You could use ByteArrayOutputStream instead of BufferedOutputStream.

ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
String fileContent = outputStream1.toString("UTF-8");
like image 180
eztam Avatar answered Sep 24 '22 13:09

eztam


To write to a stream, in memory, use: ByteArrayOutputStream

new ByteArrayOutputStream();

Another Way:

BufferedReader reader = null;
String remoteFile1 = "/Users/A/file.txt";
try {
   InputStream stream = ftpClient.retrieveFileStream(remoteFile1);
   reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
   int data;
   while ((data = reader.read()) != -1) {
      //here, do what ever you want
   }
} finally {
   if (reader != null) try { reader.close(); } catch (IOException ex) {}
}
like image 30
Shaheer Avatar answered Sep 26 '22 13:09

Shaheer