I am planning to create an application for downloading a file from FTP server, Below code has working fine with the functionality, But I need to show current speed and transfer rate while downloading a file, Please help me to solve this problem,
private boolean downloadSingleFile(String remoteFilePath, File downloadFile) {
boolean status = false;
try {
con = new FTPClient();
con.setConnectTimeout(5000);
con.connect(host);
if (con.login(username, password)) {
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
File parentDir = downloadFile.getParentFile();
if (!parentDir.exists())
parentDir.mkdir();
OutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(
new FileOutputStream(downloadFile));
con.setFileType(FTP.BINARY_FILE_TYPE);
status = con.retrieveFile(remoteFilePath, outputStream);
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
con.logout();
con.disconnect();
}
} else {
con.logout();
con.disconnect();
// delayWait(duration);
}
}
catch (UnknownHostException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e) {
}
return status;
}
If i would like to download a more than 5Mb or 50 Mb file this requirement will be useful for the user to know about the current speed of the device , Please help me to finish this issues.
Regards
Priya
Related
I am using following method to encrypt and decrypt the files. File is getting decrypted properly but I am unable to view Image or video in application. File is opening in gallery and I can view image and watch video clearly. The same I am unable to do in application using Imageview and Videoview
Below is my code :
public void run() {
boolean successful = true;
operationInProgress = true;
lastUpdateAtByteNumber = 0;
totalBytesRead = 0;
timeOperationStarted = System.currentTimeMillis();
if (operationType == OPERATION_TYPE_ENCRYPTION) {
completedMessageStringId = R.string.encryption_completed;
} else {
completedMessageStringId = R.string.decryption_completed;
}
InputStream inputStream = null;
OutputStream outputStream = null;
//get the input stream
try {
inputStream = new FileInputStream(inputFileName);
} catch (IOException ioe) {
successful = false;
ioe.printStackTrace();
}
//get the output stream
try {
outputStream = new FileOutputStream(outputFileName);
} catch (IOException ioe) {
successful = false;
ioe.printStackTrace();
}
if (inputStream != null && outputStream != null) {
//call AESCrypt
try {
fileSize = inputStream.available();
AESCrypt aesCrypt = new AESCrypt(password);
if (operationType == OPERATION_TYPE_ENCRYPTION) {
//Encrypt
aesCrypt.encrypt(version, inputStream, outputStream);
} else {
//Decrypt
aesCrypt.decrypt(fileSize, inputStream, outputStream);
}
} catch (GeneralSecurityException gse) {
successful = false;
gse.printStackTrace();
} catch (UnsupportedEncodingException uee) {
successful = false;
uee.printStackTrace();
} catch (IOException ioe) {
successful = false;
} catch (NullPointerException npe) {
successful = false;
}
}
//close the streams
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ioe) {
successful = false;
ioe.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException ioe) {
successful = false;
}
}
operationInProgress = false;
}
The reference code is https://www.aescrypt.com/download/
AndroidCrypt (AES Crypt compatible) for Android phones (source code)
File getting encrypted and decrypted properly. When I am trying to open the load the file using Imageview for image and videoview for video.
I am using below code to view image
File url1 = new File(path to my file);
Bitmap bmp = BitmapFactory.decodeFile(url1.getAbsolutePath());
objImageView.setImageBitmap(bmp);
It gives error **"libjpeg error 105 < Ss=0, Se=63, Ah=0, Al=0> from Incomplete image data"** . or **Failed to create image decoder with message 'unimplemented'**
For Video I am using below code
getPackageName is name of package
FileProvider I have declared in manifest and also in xml I have menioned fielpath
File url1 = new File(path to video file)
videoView.setVideoURI(FileProvider.getUriForFile(
this, getPackageName(),url1));
The same image and video is clearly visible in Gallery application.
Please help me.
Thanks
I am trying firstly to download the file and its content from Dropbox in Android app using Dropbox Core API but when i execute the following code the app crushes.
EDIT: I have used two functions downloadDropboxFile and copy functions. The problem is that i am getting blank data when i read the local file which is supposed to contain the dropbox file data.
Here is the code where i call the function
downloadDropboxFile("/userandpass.txt");
if (mDBApi.getSession().isLinked())
{
InputStream instream = new FileInputStream(String.valueOf(getExternalCacheDir()) + "/userandpass.txt");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
mTestOutput.setText(buffreader.readLine());
}
Here is the functions
private boolean downloadDropboxFile(String fileSelected) {
File dir = new File(String.valueOf(getExternalCacheDir()));
if (!dir.exists())
dir.mkdirs();
try {
File localFile = new File(dir + fileSelected);
if (!localFile.exists()) {
localFile.createNewFile();
copy(fileSelected, localFile);
} else {
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
private void copy(final String dbPath, final File localFile) {
new Thread(new Runnable() {
#Override
public void run() {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
try {
DropboxAPI.DropboxInputStream fd = mDBApi.getFileStream(dbPath,null);
br = new BufferedInputStream(fd);
bw = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break;
}
bw.write(buffer, 0, read);
}
} catch (DropboxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}). start();
}
Dropbox Core API Implementation on Android Studio:
On app/libs i have the:
dropbox-android-sdk-1.6.3.jar
httpmime--4.0.3.jar
json_simple-1.1.jar
Your issue is here :
if (!localFile.exists()) {
localFile.createNewFile(); //otherwise dropbox client will fail silently
}
The exception is :
java.io.IOException: open failed: EROFS (Read-only file system)
This means you're trying to create a File on a location that is read only in the phone's memory, I'm guessing the internal storage. Have a look at this excellent answer by Mark Murphy on creating a File based on locations that can be written to.
Hoping this has been of some help, happy coding ;-)
The app is to write some data every second on file. This is working in other tabs & phones but in "Lenovo IdeaTab" (4.1) is able to create directory but not able to create file to write in it.
Below is the code, I am using to write in file:
public void writeDataInFile(String dataString)
{ File logFile = null;
try {
File folder = new File(Environment.getExternalStorageDirectory() + "/file_name_xyz");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
// Do something on success
String file_path = folder+"/"+currentFileName+".txt";
logFile = new File(file_path);
if (!logFile.exists())
{
try
{
logFile.createNewFile();
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append("\nxyz: \n");
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
// Do something else on failure
Toast.makeText(getApplicationContext(), "Failed to write", Toast.LENGTH_SHORT).show();
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(dataString);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
//Write internal storage -- data/data/xyzzz
try {
FileOutputStream fos = openFileOutput(currentFileName, Context.MODE_APPEND);
fos.write(dataString.getBytes());
fos.close();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
Verify which version of Android is installed on the Tablet and then lookup file IO API in the Android Docs for that version of Android. I'm pretty sure they changed some things when it comes to accessing files in some of the later versions of the API.
I am trying to implement a simple socket that sends and receives strings from a server.
The following code is freezing the application, not sure if I have done something obviously wrong?
public String internetRoutesRetrieve(String userName) {
String command = null;
String response = null;
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("Hidden IP", HiddenPort);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
command = "SEARCH <" + userName + ">";
dataOutputStream.writeUTF(command);
response = dataInputStream.readUTF();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
Thanks
Edit: It seems the program is freezing when I am trying to save the response from the server
see AsyncTask for proper client server communication on Android application.
you'd usualy get android.os.NetworkOnMainThreadException if you don't but I'd give it a try.
I am using apache FTPClient on android. I want to download a file from ftp server. But I want check if it exists on server before downloading. How can I check this?
Thanks,
my code:
public static boolean getFile(String serverName, String userName,
String password, String serverFilePath, String localFilePath)
throws Exception {
FTPClient ftp = new FTPClient();
try {
ftp.connect(serverName);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return false;
}
} catch (IOException e) {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException f) {
throw e;
}
}
throw e;
} catch (Exception e) {
throw e;
}
try {
if (!ftp.login(userName, password)) {
ftp.logout();
}
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
OutputStream output;
output = new FileOutputStream(localFilePath);
ftp.retrieveFile(serverFilePath, output);
output.close();
ftp.noop(); // check that control connection is working OK
ftp.logout();
return true;
} catch (FTPConnectionClosedException e) {
throw e;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw e;
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException f) {
throw f;
}
}
}
}
String[] files = ftp.listnames();
look files if desired file name is include...
Assuming ftpClient is an instance of org.apache.commons.net.ftp.FTPClient:
public boolean fileExists(String fileName) throws IOException
{
String[] files = ftpClient.listNames();
return Arrays.asList(files).contains(fileName);
}
When the client sends RETR and the server responds with an error code 550 you can be pretty sure that the file does not exist or you don't have permission to fetch it... Since the FTP spec is a little loose you might just assume for any error in the range 550 - 559 which indicates permanent filesystem error.
InputStream inputStream = ftpClient.retrieveFileStream(filePath);
if (inputStream == null || ftpClient.getReplyCode() == 550) {
// it means that file doesn't exist.
}
or
FTPFile[] mFileArray = ftp.listFiles();
// you can check if array contains needed file