How to download chosen file from ftp-server using java? [duplicate] - java

With this code iI always get a empty file.
What I have to do with it?
login is always true. (ofc, here is not real password)
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import java.io.*;
public class Logs {
public static void main(String[] args) {
FTPClient client = new FTPClient();
try {
client.connect("myac.cs-server.pro", 121);
boolean login = client.login("a3ro", "passWordIsSecret");
System.out.println(login);
String remoteFile1 = "myac_20150304.log";
File downloadFile1 = new File("C:\\Users\\Aero\\Desktop\\test\\myac.log");
OutputStream outputStream1 =
new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = client.retrieveFile(remoteFile1, outputStream1);
System.out.println(success);
outputStream1.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Use FileOutputStream:
String filename = "test.txt";
FileOutputStream fos = new FileOutputStream(filename);
client.retrieveFile("/" + filename, fos);

Use something like this:
InputStream inputStream = client.retrieveFileStream(remoteFileNameHere);
To retrieve the remote file input stream.
Then you can use to copy the stream to desired file:
FileOutputStream out = new FileOutputStream(targetFile);
org.apache.commons.io.IOUtils.copy(in, out);

Related

Unzip files in FTP server using Java

I am trying to unzip files in the FTP location, but when i unzip i am not able to get all the files in FTP server, but when i try the code to unzip files to local machine it is working. I am sure somewhere while writing the data to FTP i am missing something.Below is my code. Please help me on this.
public void unzipFile(String inputFilePath, String outputFilePath) throws SocketException, IOException {
FileInputStream fis = null;
ZipInputStream zipIs = null;
ZipEntry zEntry = null;
InputStream in = null;
FTPClient ftpClientinput = new FTPClient();
FTPClient ftpClientoutput = new FTPClient();
String ftpUrl = "ftp://%s:%s#%s/%s;type=i";
ftpClientinput.connect(server, port);
ftpClientinput.login(user, pass);
ftpClientinput.enterLocalPassiveMode();
ftpClientinput.setFileType(FTP.BINARY_FILE_TYPE);
String uploadPath = "path";
ftpClientoutput.connect(server, port);
ftpClientoutput.login(user, pass);
ftpClientoutput.enterLocalPassiveMode();
ftpClientoutput.setFileType(FTP.BINARY_FILE_TYPE);
try {
// fis = new FileInputStream(inputFilePath);
String inputFile = "/Srikanth/RecordatiFRA_expenses.zip";
String outputFile = "/Srikanth/FR/";
in = ftpClientinput.retrieveFileStream(inputFile);
zipIs = new ZipInputStream(new BufferedInputStream(in));
while ((zEntry = zipIs.getNextEntry()) != null) {
try {
byte[] buffer = new byte[4 * 8192];
FileOutputStream fos = null;
OutputStream out = null;
// String opFilePath = outputFilePath + zEntry.getName();
String FTPFilePath = outputFile + zEntry.getName();
// System.out.println("Extracting file to "+opFilePath);
System.out.println("Extracting file to " + FTPFilePath);
// fos = new FileOutputStream(opFilePath);
out = ftpClientoutput.storeFileStream(FTPFilePath);
// System.out.println(out);
int size;
while ((size = zipIs.read(buffer, 0, buffer.length)) != -1) {
// fos.write(buffer, 0 , size);
out.write(buffer, 0, size);
}
// fos.flush();
// fos.close();
} catch (Exception ex) {
ex.getMessage();
}
}
zipIs.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (ftpClientinput.isConnected()) {
ftpClientinput.logout();
ftpClientinput.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
This method will do what you want, you can tweak it as you like.
I cleaned up and removed a lot that you didn't need; One thing to note is the use of try-with-resources blocks and not declaring your local variables so far from where they're used.
Your main error was that you needed to call completePendingCommand after certain methods as noted in their documentation.
Remember to read the documentation on methods you're using for the first time.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public static void unzipFTP(String server, int port, String user, String pass, String ftpPath)
throws SocketException, IOException {
FTPClient ftp = new FTPClient();
ftp.connect(server, port);
ftp.login(user, pass);
ftp.enterLocalPassiveMode();
ftp.setFileType(FTP.BINARY_FILE_TYPE);
try (InputStream ftpIn = ftp.retrieveFileStream(ftpPath);
ZipInputStream zipIn = new ZipInputStream(ftpIn);) {
// complete and verify the retrieve
if (!ftp.completePendingCommand()) {
throw new IOException(ftp.getReplyString());
}
// make the output un-zipped directory, should be unique sibling of the target zip
String outDir = ftpPath + "-" + System.currentTimeMillis() + "/";
ftp.makeDirectory(outDir);
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
throw new IOException(ftp.getReplyString());
}
// write the un-zipped entries
ZipEntry zEntry;
while ((zEntry = zipIn.getNextEntry()) != null) {
try (OutputStream out = ftp.storeFileStream(outDir + zEntry.getName());) {
zipIn.transferTo(out);
}
if (!ftp.completePendingCommand()) {
throw new IOException(ftp.getReplyString());
}
}
} finally {
try {
if (ftp.isConnected()) {
ftp.logout();
ftp.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

How to get PDF file from web using java streams

I need to download PDF file from web, for example http://www.math.uni-goettingen.de/zirkel/loesungen/blatt15/loes15.pdf this link. I have to do it using Streams. With images it works fine by me :
public static void main(String[] args) {
try {
//get the url page from the arguments array
String arg = args[0];
URL url = new URL("https://cs7065.vk.me/c637923/v637923205/25608/AD8WhOSx1ic.jpg");
try{
//jpg
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[131072];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream("borrowed_image.jpg");
fos.write(response);
fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
But with PDf it does not work. What could be the problem ?
I made minor edits to your code to fix syntax errors and, this seems to work (below). Consider placing your close() statements in a finally block.
package org.snb;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class PdfTester {
public static void main(String[] args) {
//get the url page from the arguments array
try{
//String arg = args[0];
URL url = new URL("http://www.pdf995.com/samples/pdf.pdf");
//jpg
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[131072];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream("/tmp/bart.pdf");
fos.write(response);
fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
try this, this got the job done (and pdf is readable).
see if there are any exceptions thrown when requesting the url.
public static void main(String[] args) {
try {
//get the url page from the arguments array
URL url = new URL("http://www.math.uni-goettingen.de/zirkel/loesungen/blatt15/loes15.pdf");
try {
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[131072];
int n = 0;
while (-1 != (n = in.read(buf))) {
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream("loes15.pdf");
fos.write(response);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}

Java BufferedWriter and OutputStream .close() method

I'm new in java and there is a question about BufferedWriter and OutputStream closing.
I have some logic, where it is inconvenient to use try-with-resources:
public static void writeFile(String fileName, String encoding, String payload) {
BufferedWriter writer = null;
OutputStream stream = null;
try {
boolean needGzip = payload.getBytes(encoding).length > gzipZize;
File output = needGzip ? new File(fileName + ".gz") : new File(fileName);
stream = needGzip ? new GZIPOutputStream(new FileOutputStream(output)) : new FileOutputStream(output);
writer = new BufferedWriter(new OutputStreamWriter(stream, encoding));
writer.write(payload);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
So, i have to close all resources by myself. Should i close OutputStream AND BufferedWriter? Or it is ok to close just BufferedWriter?
Is everything ok with my code?
No, Leave it to Java, let it handle it:
public static void writeFile(String fileName, String encoding,
String payload) {
boolean needGzip = payload.getBytes(Charset.forName(encoding)).length > gzipZize;
File output = needGzip ? new File(fileName + ".gz")
: new File(fileName);
try (OutputStream stream = needGzip ? new GZIPOutputStream(
new FileOutputStream(output)) : new FileOutputStream(output);
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(stream, encoding))) {
writer.write(payload);
} catch (IOException e) {
e.printStackTrace();
}
}
It is OK to just close the BufferedWriter. If you follow the Javadoc you will see that it closes all nested streams.
If you close BufferedWriter its stream will be closed too but BufferedWriter and OutputStream both implements Closeable. So if you want you can just use try with resource to handle the close for you
for example :
public static void writeFile(String fileName, String encoding, String payload) {
File output = new File(fileName);
try (OutputStream stream = new FileOutputStream(output);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, encoding))) {
writer.write(payload);
} catch (IOException e) {
e.printStackTrace();
}
}
Edit: Added getStream to check if it needs gzip stream or no
Note: This answer is just an "update" of your code, i'm not sure what are you trying to do in general, so it may not be the best solution for your program
public static void writeFile(String fileName, String encoding, String payload) {
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(getStream(fileName, encoding, payload), encoding))) {
writer.write(payload);
} catch (IOException e) {
e.printStackTrace();
}
}
public static OutputStream getStream(String fileName, String encoding, String payload) throws IOException {
boolean needGzip = payload.getBytes(encoding).length > gzipZize;
File output = needGzip ? new File(fileName + ".gz") : new File(fileName);
return needGzip ? new GZIPOutputStream(new FileOutputStream(output)) : new FileOutputStream(output);
}

Read and Write text file from my own class in Android Studio

I have been trying to create a class called TextFileReaderWriter I want to use the getters and setters to read and write to a text file in such a way that I can call the class and the method from anywhere in the program by simply using setfileContents(somestring) and somestring = getfileContents() something like this
example:
TextFileReaderWriter trw = new TextFileReaderWriter();
trw.setfileContents(somestring); //this would write 'somestring' to the text file.
String somestring = trw.getfileContents(); //this would return 'somestring' from the text file.
Here's what I have so far but it writes nothing to the file:
public class TextFileReaderWriter extends Activity{
String fileContents;
Context context;
String TAG = "MYTAG";
public TextFileReaderWriter(String fileContents, Context context) {
this.fileContents = fileContents;
this.context = context;
}
public String getFileContents() {
return fileContents;
}
public void setFileContents(String fileContents) {
this.fileContents = fileContents;
FileOutputStream fos = null;
try {
fos = context.openFileOutput("UserInputStore", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fos);
try {
osw.write(fileContents);
Log.d(TAG, fileContents);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You don't need the OutputStreamWriter--FileOutputStreamwill do the trick just fine.
//what you had before
FileOutputStream fos = null;
try {
fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//use just the file output stream to write the data
//data here is a String
if (fos != null) {
try {
fos.write(data.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Method to save data on disk :
protected static void saveDataOnDisk(String data) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
ObjectOutput objectOutput = new ObjectOutputStream(byteArrayOutputStream);
objectOutput.writeObject(data);
byte[] buffer = byteArrayOutputStream.toByteArray();
File loginDataFile = (new File(filePath)); // file path where you want to write your data
loginDataFile.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(loginDataFile);
fileOutputStream.write(buffer);
fileOutputStream.close();
objectOutput.flush();
objectOutput.close();
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
Log.i(“SAVE”, ”———————-DONE SAVING”);
} catch(IOException ioe) {
Log.i(“SAVE”, “———serializeObject|”+ioe);
}
}
Method to fetch data from disk:
private static Object getDataFromDisk() {
try {
FileInputStream fileInputeStream = new FileInputStream(FilePath);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputeStream);
Object data = (Object) objectInputStream.readObject();
objectInputStream.close();
fileInputeStream.close();
return dataModel;
} catch (Exception error) {
Log.i(“FETCH”, ”—-getDataFromDisk———ERROR while reading|” + error);
}
return null;
}

Checking if file exists, if so, dont create new file and append instead

private void saveFormActionPerformed(java.awt.event.ActionEvent evt) {
name = nameFormText.getText();
surname = surnameFormText.getText();
age = Integer.parseInt(ageFormText.getText());
stadium = stadiumFormText.getText();
Venues fix = new Venues();
fix.setName(name);
fix.setSurname(surname);
fix.setAge(age);
fix.setStadium(stadium);
File outFile;
FileOutputStream fStream;
ObjectOutputStream oStream;
try {
outFile = new File("output.data");
fStream = new FileOutputStream(outFile);
oStream = new ObjectOutputStream(fStream);
oStream.writeObject(fix);
JOptionPane.showMessageDialog(null, "File written successfully");
oStream.close();
} catch (IOException e) {
System.out.println(e);
}
}
This is what I have so far. Any ideas on what I could do with it to append the file if it's already created?
You have first to check if the file exists before, if not create a new one. To learn how to append object to objectstream take a look at this question.
File outFile = new File("output.data");
FileOutputStream fStream;
ObjectOutputStream oStream;
try {
if(!outFile.exists()) outFile.createNewFile();
fStream = new FileOutputStream(outFile);
oStream = new ObjectOutputStream(fStream);
oStream.writeObject(fix);
JOptionPane.showMessageDialog(null, "File written successfully");
oStream.close();
} catch (IOException e) {
System.out.println(e);
}
Using Java 7, it is simple:
final Path path = Paths.get("output.data");
try (
final OutputStream out = Files.newOutputStream(path, StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
final ObjectOutputStream objOut = new ObjectOutputStream(out);
) {
// work here
} catch (IOException e) {
// handle exception here
}
Drop File!

Categories