Error when connecting to FTP using apache commons - java

I am using apache common library for connecting to FTP with Android app.
Now I want to upload a file from internal storage to FTP server and I get this reply from getReplyString() method.
And I get this msg
553 Can't open that file: Permission denied
//Write file to the internal storage
String path = "/sdcard/";
File file = new File(path, fileName);
FileOutputStream stream = null;
try {
stream = new FileOutputStream(file);
stream.write(jsonObject.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Read the file from resources folder.
try {
File file1 = new File(path, fileName);
Log.d("path",file1.getPath());
BufferedInputStream in = new BufferedInputStream (new FileInputStream (file1.getPath()));
client.connect(FTPHost);
client.login(FTPUserName, FTPPassword);
client.enterLocalPassiveMode();
client.setFileType(FTP.BINARY_FILE_TYPE);
// Store file to server
Log.d("reply",client.getReplyString());
boolean res = client.storeFile("/"+fileName, in);
Log.d("reply",client.getReplyString());
Log.d("result",res+"");
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

how to make the file uploading to ftp faster

we are using below code to upload files back to the FTP server?
basically 60 MB file is taking 3 minutes to upload to ftp server.Is there any way to make it faster?Please note that uploadable file(input file) and ftp server, both are on the same host but still its taking this much time.
at this line client.storeFile(filename, fis) its taking maximum time.
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("ftp.domain.com");
client.login("admin", "secret");
//
// Create an InputStream of the file to be uploaded
//
String filename = "sample.zip";
fis = new FileInputStream(filename);
//
// Store file to server
//
client.storeFile(filename, fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}

Android: Saving .png from URL into app internal storage

I'm relatively new to android, and I'm trying to modify an android app such that it downloads a profile picture (preferably in PNG) from a URL, and saves it in the com.companyName.AppName.whatever/files. It should be noted that the app was initially created in Unity, and just built and exported.
Here's my initial code:
URL url = null;
try {
url = new URL(playerDO.getProfileURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
InputStream input = null;
try {
input = url.openStream();
} catch (IOException e) {
e.printStackTrace();
}
String fileName = playerDO.getId() + ".png";
FileOutputStream outputStream = null;
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
byte[] buffer = new byte[256];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT: Here's my other code, as suggested by #Ashutosh Sagar
InputStream input = null;
Bitmap image = null;
try {
input = url.openStream();
image = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String fileName = playerDO.getId() + ".png";
FileOutputStream outputStream = null;
File myDir = getFilesDir();
try {
Log.wtf("DIRECTORY", myDir.toString());
File imageFile = new File(myDir, fileName);
if (!imageFile.exists()){
imageFile.createNewFile();
Log.wtf("ANDROID NATIVE MSG: WARN!", "File does not exist. Writing to: " + imageFile.toString());
}
outputStream = new FileOutputStream(imageFile, false);
image.compress(Bitmap.CompressFormat.PNG, 90, outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
Log.wtf("AWWW CRAP", e.toString());
}
}
(It doesn't write either).
Unfortunately, I've had several problems with this. My primary issue is that when it (on the cases that it does) runs, it actually doesn't save anything. I'll go and check com.companyName.AppName.whatever/files directory only to find no such .png file. I will also need it to overwrite any existing files of the same name, which is hard to check when it doesn't work.
My secondary issue is that it fails to take into account delays in internet connection. Although I've put in enough try-catch clauses to stop it from crashing (as it used to), the end result is that it also doesn't save.
How can I improve upon this? Anything I'm missing?
EDIT:
Printing out the directory reveals it should be in:
/data/user/0/com.appName/files/5965e9e4a0f0463853016e2b.png
However, using ES File explorer, the only thing remotely close to that is
emulated/0/Android/data/com.appName/files/
Are they the same directory?
try this first get bitmap image from url
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
and to save bitmap image please check the ans of GoCrazy
Try this
void getImage(String string_url)
{
//Generate Bitmap from URL
URL url_value = new URL(string_url);
Bitmap image =
BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
//Export File to local Directory
OutputStream stream = new FileOutputStream("path/file_name.png");
/* Write bitmap to file using JPEG or PNG and 80% quality hint for JPEG. */
bitmap.compress(CompressFormat.PNG, 80, stream);
stream.close();
}

How to save audio files and send them

I'm trying to save an audio file to send it to whatsapp, but i am unable to save it on external storage. I am not getting where am I making mistakes.
I am using this code:
FileOutputStream outputStream;
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES), "FUNG");
if (!file.mkdirs()) {}
try {
outputStream = new FileOutputStream(file);
outputStream.write(R.raw.badum2);
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Intent shareIntent = new Intent(Intent.ACTION_SEND);
Uri uri = Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES) + "/FUNG/badum2.m4a");
shareIntent.setType("audio/m4a");
shareIntent.setPackage("com.whatsapp");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(shareIntent);
When the file is sent to WhatsApp, it shows error like:
"fail to share, please try again"
I don't see the audio file in directory, so I guess the error is that I am making some mistakes in saving audio files on external storage.
Please help me in solving this.
I see multiple problems:
(1) if (!file.mkdirs()) {} creates a directory at the path of file, later you use that directory to open an output stream, which of course does not work.
Solution:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES), "FUNG/badum2.m4a"); // assumed target file
if (!file.getParentFile().mkdirs() && !file.getParentFile().isDirectory()) {
// Abort! Directory could not be created!
}
(2) outputStream.write(R.raw.badum2); will write the int value referring
to your resource, not the resource itself.
Solution:
Use InputStream in = ctx.getResources().openRawResource(R.raw.badum2); where ctx is a Context instance (e.g. your Activity) and write its content to the file.
try {
outputStream = new FileOutputStream(file);
try {
InputStream in = ctx.getResources().openRawResource(R.raw.badum2);
byte[] buffer = new byte[4096];
int read;
while ((read = in.read(buffer, 0, buffer.length) >= 0) {
outputStream.write(buffer, 0, read);
}
in.close();
} catch (IOException ex) {
ex.printStackTrace();
}
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Can't read a file for strange reason [duplicate]

This question already has answers here:
Why I can't read a read only file?
(2 answers)
Closed 9 years ago.
I have these methods for reading and writing to a file:
/* Write content to a file */
private void writeToFile(ArrayList<String> list) {
File file = new File("jokesBody1.bjk");
FileOutputStream fos;
if(list != null){
try {
file.createNewFile();
fos = openFileOutput("jokesBody1.bjk",Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(list);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
file.createNewFile();
fos = openFileOutput("jokesBody1.bjk",Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject("");
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/* Read file's content */
private ArrayList<String> readFromFile() {
File file = new File("jokesBody1.bjk");
ArrayList<String> list = new ArrayList<String>();
try {
file.createNewFile();
ObjectInputStream ois = new ObjectInputStream( new FileInputStream( file ) );
try {
list = (ArrayList)ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ois.close();
} catch (IOException e) {
Log.e("log activity", "Can not read file: " + e.toString());
}
return list;
}
Everyrhing seems to be fine to me, but when I run the code I'm getting the following error:
02-15 17:02:07.655: E/log activity(1882): Can not read file: java.io.IOException: open failed: EROFS (Read-only file system)
Why the system is read only? Should I do something when I'm creating the file if it does not exist by file.createNewFile();?
I know that I'm missing something extremely small, but as a total beginner, I'm not able to spot it.
You get this error probably on Linux.
This file system is mounted as read-only.
So you cannot write to it.

Unable to Upload file on FTP Server in android

I am trying to Upload file like this
try {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString
FTPClient ftpClient = new FTPClient();
ftpClient.connect("xxx.xxx.xx.xx");
if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))
{
boolean status=ftpClient.login("username", "password");
Log.d(TAG, "login status=="+status);
status=ftpClient.changeWorkingDirectory("New directory");
Log.d(TAG, "changeWorkingDirectory status=="+status);
status=ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
Log.d(TAG, "setFileType status=="+status);
ftpClient.enterLocalPassiveMode();
String srcFilePath=extStorageDirectory + "/AA.txt";
FileInputStream srcFileStream = new FileInputStream(new File(srcFilePath));
status=ftpClient.storeFile("AA.txt", srcFileStream);
Log.d(TAG, "upload status=="+status);
ftpClient.logout();
ftpClient.disconnect();
}
else
{
Log.d(TAG, "connectfail");
}
} catch (SocketException e) {
Log.d(TAG, "SocketException status=="+e.toString());
e.printStackTrace();
} catch (FileNotFoundException e) {
Log.d(TAG, "FileNotFoundException status=="+e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.d(TAG, "IOException status=="+e.toString());
e.printStackTrace();
}
below is my logcat status
07-11 12:24:43.359: D/FTPDownloadDroid(10647): <!>com.ss.dr 138<!> login status==true
07-11 12:24:48.379: D/FTPDownloadDroid(10647): <!>com.ss.dr 141<!> changeWorkingDirectory status==true
07-11 12:24:48.859: D/FTPDownloadDroid(10647): <!>com.ss.dr 143<!> setFileType status==tr
07-11 12:24:54.359: D/FTPDownloadDroid(10647): <!>com.ss.dr 150<!> upload status==false
I want to Upload file on "New Directory" folder and file name AA.txt ** but it is giving Upload status false.**
Is the problem in server or in my Code???
Please help!!!!!!!!!
Thanks in advance
Try my code below, i used this to upload and download a song on the server. I am using the Apache's common lib.
Please make the changes for the directories and file name in the below code.
UPLOAD:
public void goforIt(){
FTPClient con = null;
try
{
con = new FTPClient();
con.connect("192.168.2.57");
if (con.login("Administrator", "KUjWbk"))
{
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = "/sdcard/vivekm4a.m4a";
FileInputStream in = new FileInputStream(new File(data));
boolean result = con.storeFile("/vivekm4a.m4a", in);
in.close();
if (result) Log.v("upload result", "succeeded");
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
DOWNLOAD:
public void goforIt(){
FTPClient con = null;
try
{
con = new FTPClient();
con.connect("192.168.2.57");
if (con.login("Administrator", "KUjWbk"))
{
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = "/sdcard/vivekm4a.m4a";
OutputStream out = new FileOutputStream(new File(data));
boolean result = con.retrieveFile("vivekm4a.m4a", out);
out.close();
if (result) Log.v("download result", "succeeded");
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
Log.v("download result","failed");
e.printStackTrace();
}
}

Categories

Resources