Downloading files from FTP - java

I'm trying to download files from FTP on Java using org.apache.commons.
try {
OutputStream os = new FileOutputStream(downloadedFile);
boolean success = this.client.retrieveFile(from, os);
System.out.println("File transfer status is "+ Boolean.toString(success));
os.close();
} catch (IOException e) {
System.err.println(e.getMessage());
}
And files are downloading, but some images have error like Invalid image, another looks like that
https://www.dropbox.com/s/faozfxzag5xrk5z/Screenshot_3.png
Any ideas? Thx

Try setting file type to binary, ie:
client.setFileType(FTP.BINARY_FILE_TYPE);
FTPClient has default settings to use FTP.ASCII_FILE_TYPE.

Related

How to save an PNG via code in a Runnable JAR file?

I'm having trouble fixing this issue,
I have created a Client\Server side application and created a Method where a user can
"Send" a PNG file from his side to Server side, then the Server side "Creates" and saves the image in a Package that only contains pictures.
When i run this Method of sending a Picture from Client side to Server side via Eclipse IDE
it works as expected, but when exporting Client/Server side into Runnable JAR files, i get the next error:
Java
private static void getImg(MyFile msg) {
int fileSize =msg.getSize();
System.out.println("length "+ fileSize);
try {
File newFile = new File(System.getProperty("user.dir")+"\\src\\GuiServerScreens\\"+msg.getFileName());
FileOutputStream fileOut;
fileOut = new FileOutputStream(newFile);
BufferedOutputStream bufferOut = new BufferedOutputStream(fileOut);
try {
bufferOut.write(msg.getMybytearray(), 0, msg.getSize());
fileOut.flush();
bufferOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I get the follow error :
java.io.FileNotFoundException: java.io.FileNotFoundException: C:\Users\Ilya\Desktop\src\GuiServerScreens\test.png (The system cannot
find the path specified)
It seems that using File newFile = new File(System.getProperty("user.dir")+"\\src\\GuiServerScreens\\"+msg.getFileName());
Does not provide the wanted result
I think you are mixing what your directories look like in netbeans with what's available on the server. Save to an external directory instead, not to your src directory.

After File compression I lost the Filename extension

I am trying to compress my file using the ZipOutPutStream. I tried below code and got the compressed folder with the file. But when I am extracting the folder using 7Zip, the fileName extension is missing.
Also I am unable to extract the folder by normal Extract option provided in Windows.
Below is the code I tried Using Java -8
public void compress(String compressed , String raw) {
Path pCompressed = null;
try {
pCompressed = Files.createFile(Paths.get(compressed));
try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(pCompressed))) {
Path pRaw = Paths.get(raw);
Files.walk(pRaw).filter(path -> !Files.isDirectory(path)).forEach(path -> {
ZipEntry zipEntry = new ZipEntry(pRaw.relativize(path).toString());
try {
zos.putNextEntry(zipEntry);
Files.copy(path, zos);
zos.closeEntry();
} catch (IOException e) {
logger.error("Exception while copying file to compressed Directory: "+e);
}
});
}
catch(IOException ioe) {
logger.error("Exception while compressing the output file: "+ioe);
}
}
catch (IOException e1) {
logger.error("Exception While Path initialization for compressing the file");
}
}
Expecting : After Extraction someFolder/MyFile.csv
I've just tried this code and when I provided it with compressed = "out.zip" and raw = "testdir", it worked fine for me. It produced a zip file containing the contents of testdir. I was then able to extract this with 7Zip and the built in Windows extraction and the files were all present and correct.
My guess is that you have not specified the .zip extension for the output file or that Windows is hiding the extension in the folder view. (I think it does this by default.)

Copy file from Android to Windows

I wrote a small app, which creats a XML file on my Android device. No I try to copy it from my phone to my Windows PC. In Windows Explorer I can't see this file specific file, on my phone I can see this file with various file explorers. When I reboot my phone, the file appears in Windows Explorer, but I can't copy it to my desktop.
Here is my code which creates my file:
String filename = "myfile.xml";
String dir = Environment.getExternalStorageDirectory().getPath()+"/"+c.getResources().getString(R.string.app_name);
createDir(dir);
File file = new File(dir,filename);
FileWriter out=null;
try {
String xml = createXml();
try {
out = new FileWriter(file);
out.write(xml);
out.close();
} catch (Exception e) {
out.close();
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
My guess is, this code doesn't free the file handle so Androids MTP cannot access this file. This would also explain, why the file is shown and could be deleted (but not able to be transfered to my PC) after rebooting my phone.
Any suggestions what goes wrong?
I think you should refresh the media scanner for that file
sendBroadcast(
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageAdded))
);

Java FTP commons-net error downloading files

I'm using apache commons.net to access an ftp site which is the directory is in unix:
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
I'm looping thru a list with the names of the filenames I want to download on a specific ftp site
String ftpPath = "/home/user1/input/";
FileOutputStream fos = null;
File file;
try {
for (int i = 0; i < fileList.size(); i++) {
file = new File(ftpPath+fileList.get(i).toString());
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(file));
boolean download = ftpClient.retrieveFile("c:/test/downloadedFile.csv", outputStream1);
outputStream1.close();
if (download) {
System.out.println("File downloaded successfully !");
} else {
System.out.println("Error in downloading file ! " + downloadFile);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But once I try to start to download the files I get this error althougth checking the ftp site the file exists under /home/user1/input/TejasSDH_PM_AU_09_07_2014_09_00.csv -rw-r--r--:
java.io.FileNotFoundException: \home\user1\input\TejasSDH_PM_AU_09_07_2014_09_00.csv (The system cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
at java.io.FileOutputStream.<init>(FileOutputStream.java:110)
at com.syntronic.client.FTPDataExtract$1.downloadTejasFiles(FTPDataExtract.java:255)
at com.syntronic.client.FTPDataExtract$1.run(FTPDataExtract.java:133)
I'm thinking as the ftp site I'm connecting, the path dir is in unix home/user1/input and java is converting all the "/" to "\". Anyone has an idea on what the error in eclipse means or is something wrong with my code? thank you
You seem to be switching things around.
You are opening a file outputstream to \home\user1\input\TejasSDH_PM_AU_09_07_2014_09_00.csv and you seem to be on windows so it won't work.
You have the local path where the ftp path should go and the other way around.
Please read your errors more carefully, I'm willing to bet that line 255 in FTPDataExtract.java is:
fos = new FileOutputStream(downloadFile);
Which should alert you to the fact that it's not actually an ftp problem.
for (int i = 0; i < fileList.size(); i++) {
OutputStream output;
output = new FileOutputStream("C:/test/" + fileList.get(i).toString());
ftpClient.retrieveFile(ftpPath + fileList.get(i).toString(), output);
output.close();
}
I wrongfully switch the remote and local path, switching it properly will run the program smoothly.

zip the files which are present at one FTP location and copy to another FTP location directly

I want to create zip file of files which are present at one ftp location and Copy this zip file to other ftp location without saving locally.
I am able to handle this for small size of files.It works well for small size files 1 mb etc
But if file size is big like 100 MB, 200 MB , 300 MB then its giving error as,
java.io.FileNotFoundException: STOR myfile.zip : 550 The process cannot access the
file because it is being used by another process.
at sun.net.ftp.FtpClient.readReply(FtpClient.java:251)
at sun.net.ftp.FtpClient.issueCommand(FtpClient.java:208)
at sun.net.ftp.FtpClient.openDataConnection(FtpClient.java:398)
at sun.net.ftp.FtpClient.put(FtpClient.java:609)
My code is
URLConnection urlConnection=null;
ZipOutputStream zipOutputStream=null;
InputStream inputStream = null;
byte[] buf;
int ByteRead,ByteWritten=0;
***Destination where file will be zipped***
URL url = new URL("ftp://" + ftpuser+ ":" + ftppass + "#"+ ftppass + "/" +
fileNameToStore + ";type=i");
urlConnection=url.openConnection();
OutputStream outputStream = urlConnection.getOutputStream();
zipOutputStream = new ZipOutputStream(outputStream);
buf = new byte[size];
for (int i=0; i<li.size(); i++)
{
try
{
***Souce from where file will be read***
URL u= new URL((String)li.get(i)); // this li has values http://xyz.com/folder
/myPDF.pdf
URLConnection uCon = u.openConnection();
inputStream = uCon.getInputStream();
zipOutputStream.putNextEntry(new ZipEntry((String)li.get(i).substring((int)li.get(i).lastIndexOf("/")+1).trim()));
while ((ByteRead = inputStream .read(buf)) != -1)
{
zipOutputStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
zipOutputStream.closeEntry();
}
catch(Exception e)
{
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream .close();
}
catch (Exception e) {
e.printStackTrace();
}
}
if (zipOutputStream != null) {
try {
zipOutputStream.close();
} catch (Exception e){
e.printStackTrace();
}
}
Can anybody let me know how I can avoid this error and handle large files
This is unrelated to file sizes; as the error says, you can't replace the file because some other process is currently locking it.
The reason why you see it more often with large files is because these take longer to transfer hence the chance of concurrent accesses is higher.
So the only solution is to make sure that no one uses the file when you try to transfer it. Good luck with that.
Possible other solutions:
Don't use Windows on the server.
Transfer the file under a temporary name and rename it when it's complete. That way, other processes won't see incomplete files. Always a good thing.
Use rsync instead of inventing the wheel again.
Back in the day, before we had network security, there were FTP servers that allowed 3rd party transfers. You could use site specific commands and send a file to another FTP server directly. Those days are long gone. Sigh.
Ok, maybe not long gone. Some FTP servers support the proxy command. There is a discussion here: http://www.math.iitb.ac.in/resources/manuals/Unix_Unleashed/Vol_1/ch27.htm

Categories

Resources