java.io.FileNotFoundException: /: open failed: EISDIR (Is a directory) - android

File albumF = getVideoAlbumDir();
String path = albumF.getAbsolutePath();
// path =/storage/emulated/0/Pictures/.MyImages (Hidden folder)
// fileSelected.fileName()=IMG_20140417_113847.jpg
File localFile = new File(path + "/" + fileSelected.fileName());
Log.v("", "file exist===" + localFile.exists());
if (!localFile.exists()) {
Log.v("", "inside if===");
Log.v("", "Parent Filet===" + localFile.getParentFile());
localFile.getParentFile().mkdirs();
// localFile.createNewFile();
copy(fileSelected, localFile);
} else {
Log.v("", "inside else===");
mCurrentPhotoPath = localFile.getAbsolutePath();
uploadMediaFile();
}
This copy method copies data from dropbox file to my local storage.
private void copy(final Entry fileSelected, final File localFile) {
final ProgressDialog pd = ProgressDialog.show(ChatActivity.this,
"Downloading...", "Please wait...");
new Thread(new Runnable() {
#Override
public void run() {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
DropboxInputStream fd;
try {
fd = mDBApi.getFileStream(fileSelected.path,
localFile.getAbsolutePath());
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);
}
pd.dismiss();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
android.os.Message msg = new android.os.Message();
msg.arg1 = 100;
if (msg.arg1 >= 100) {
progressHandler.sendMessage(msg);
mCurrentPhotoPath = localFile.getAbsolutePath();
}
} catch (DropboxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
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();
I am creating file in a folder using localFile.getParentFile().mkdirs();
I got above error when I upload this file to server.
how to fix this?

If you've tried all other options - and problem still persists - then maybe you have a case when the file you want to create matches name of already existing directory.(which might be earlier created my some call to mkdirs() maybe accidentally).
Example:
You want to save file Test\test.pdf but you already have folder Test\Test.pdf\

Related

Android: Failed to read Data Meta Data

I have dat file, which is binary file.It currently inside raw folder on my project.
I want to use the file in my program.
I want to copy it to certain location on the device but when executing the method, I am getting the error "Failed to read Data Meta Data"
Here is the method:
public void copyRawOnSdCard(){
File sdcard = Environment.getExternalStorageDirectory();
String targetPath = sdcard.getAbsolutePath() + File.separator + "shape_predictor_68_face_landmarks.dat";
File file = new File(targetPath);
if (!file.exists())
{
final ProgressDialog pd; pd = ProgressDialog.show(this, "Copy Files for the First Time", "Please wait",
true);
pd.show();
InputStream in = getResources().openRawResource(
getResources().getIdentifier("shape_predictor_68_face_landmarks",
"raw", getPackageName()));
FileOutputStream out = null;
try {
out = new FileOutputStream(targetPath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
in.close();
}catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
pd.cancel();
}
}
Ideas?
Thanks
Apparently There is another implementation solution and that is to put it the .dat binary file in assets folder.
And here is the implementation:
https://stackoverflow.com/questions/4447477/how-to-copy-files-from-assets-folder-to-sdcard
And it worked for me.

Android Core API Download File

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 ;-)

Download all types of file from Dropbox

I am working on Dropbox. I see the documentation. This is my code to display list:
Entry entryCheck = mApi.metadata("/", 100, null, true, null);
Log.i("Item Name", entryCheck.fileName());
Log.i("Is Folder", String.valueOf(entryCheck.isDir));
I got all list from dropbox but my question is that
Here entryCheck.isDir always give me true value if it is file or directory so how i can know which is file or which one is directory?
How i downloaded that files.
I tried with this but it is not working:
private boolean downloadDropboxFile(String dbPath, File localFile,
DropboxAPI<?> api) throws IOException {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
try {
if (!localFile.exists()) {
localFile.createNewFile(); // otherwise dropbox client will fail
// silently
}
DropboxInputStream fin = mApi.getFileStream("dropbox", dbPath);
br = new BufferedInputStream(fin);
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) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// in finally block:
if (bw != null) {
bw.close();
}
if (br != null) {
br.close();
}
}
return true;
}
This will work
String inPath ="mnt/sdcard/"+filename;
File file=new File(inPath);
try {
mFos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
mErrorMsg = "Couldn't create a local file to store the image";
return false;
}
mApi.getFile("/"+filename, null, mFos, null);
This downloads the file and store it in the sdcard location inPath.
You have to do it in a new thread,not in main thread.Use AsyncTask.
http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html
this link explains why..

Download file from Dropbox and save it into SDCARD

Am really frustated now..I want to download a file from Dropbox and save that file into SDCARD..and I got the code as:
private boolean downloadDropboxFile(String dbPath, File localFile) throws IOException{
BufferedInputStream br = null;
BufferedOutputStream bw = null;
try {
if (!localFile.exists()) {
localFile.createNewFile(); //otherwise dropbox client will fail silently
}
FileDownload fd = api.getFileStream("dropbox", dbPath, null);
**br = new BufferedInputStream(fd.is);**
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);
}
} finally {
//in finally block:
if (bw != null) {
bw.close();
}
if (br != null) {
br.close();
}
}
return true;
}
Here I am getting an error on br=new BufferedInputStream line..Pls help
I found the way:
File file= new File("/sdcard/New_csv_file.csv");
OutputStream out= null;
boolean result=false;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
DropboxFileInfo info = mApi.getFile("/photos/New_csv_file.csv", null, out, null);
Log.i("DbExampleLog", "The file's rev is: " + info.getMetadata().rev);
Intent JumpToParseCSV=new Intent(context,ParseCSV.class);
JumpToParseCSV.putExtra("FileName", file.getAbsolutePath());
Log.i("path", "FileName"+ file.getAbsolutePath());
((Activity) context).finish();
context.startActivity(JumpToParseCSV);
result=true;
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while downloading.");
file.delete();
result=false;
}
return result;
Thanks all....

Android FTPClient - retrieveFileStream() always returns null

I am a newbie to Android. I am trying download a file from ftp server to sdcard using Apache Commons FTPClient. The line InputStream input = client.retrieveFileStream("/" + fileName); always returns null. But the file is there in Ftp location. Kindly help me to know where the mistake is.
I have set the following permissions in my manifest; android:name="android.permission.INTERNET" and android:name="android.permission.WRITE_EXTERNAL_STORAGE"
My Code
private static void downLoad(){
FTPClient client = new FTPClient();
FileOutputStream fos = null;
try {
client.connect("ftp.doamin.com");
client.login("8888", "8888");
String filePath = "/mnt/sdcard/download/CheckboxHTML.txt" ;
String fileName = "CheckboxHTML.txt";
fos = new FileOutputStream(filePath);
InputStream input = client.retrieveFileStream("/" + fileName);
byte[] data = new byte[1024];
int count = input.read(data);
while ((count = input.read(data)) != -1) {
fos.write(data, 0, count);
}
fos.close();
if(!client.completePendingCommand()) {
client.logout();
client.disconnect();
System.err.println("File transfer failed.");
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Thanks for your time and interest. Ananth.
AFAIK. You are suppose to finalize file transfers by calling completePendingCommand() and verifying that the transfer was indeed successful. i.e. you need to add call the function below fos.clos().
fos.close();
client.completePendingCommand()
You may also consider this, according to the API for FTPClient.retrieveFileStream(), the method returns null when it cannot open the data connection, in which case you should check the reply code (e.g. getReplyCode(), getReplyString(), getReplyStrings()) to see why it failed.
File file = new File(Environment.getExternalStorageDirectory() + "/pdf");
if(!file.exists())
file.mkdir(); //directory is created;
try {
ftp = new FTPClient();
ftp.connect("yours ftp URL",21);//don't write ftp://
try {
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
throw new Exception("Connect failed: " + ftp.getReplyString());
}
if (!ftp.login("username","password")) {
throw new Exception("Login failed: " + ftp.getReplyString());
}
try {
ftp.enterLocalPassiveMode();
if (!ftp.setFileType(FTP.BINARY_FILE_TYPE)) {
// Log.e(TAG, "Setting binary file type failed.");
}
transferFile(ftp);
} catch(Exception e) {
// handleThrowable(e);
} finally {
if (!ftp.logout()) {
// Log.e(TAG, "Logout failed.");
}
}
} catch(Exception e) {
// handleThrowable(e);
} finally {
ftp.disconnect();
}
} catch(Exception e) {
// handleThrowable(e);
}
}
private void transferFile(FTPClient ftp) throws Exception {
long fileSize=0;
fileSize = getFileSize(ftp, "nag.pdf");
Log.v("async","fileSize"+fileSize);
if(!(fileSize==0)){
InputStream is = retrieveFileStream(ftp, "nag.pdf");
downloadFile(is, fileSize);
is.close();
}
else
//nosuch files
if (!ftp.completePendingCommand()) {
throw new Exception("Pending command failed: " + ftp.getReplyString());
}
}
private InputStream retrieveFileStream(FTPClient ftp, String filePath)
throws Exception {
InputStream is = ftp.retrieveFileStream(filePath);
int reply = ftp.getReplyCode();
if (is == null
|| (!FTPReply.isPositivePreliminary(reply)
&& !FTPReply.isPositiveCompletion(reply))) {
throw new Exception(ftp.getReplyString());
}
return is;
}
private byte[] downloadFile(InputStream is, long fileSize)
throws Exception {
outputStream os = newFileOutputStream(Environment.getExternalStorageDirectory()
+ "/pdf/nag.pdf");
byte[] buffer = new byte[(int) fileSize];
int readCount;
while( (readCount = is.read(buffer)) > 0) {
os.write(buffer, 0, readCount);
}
Log.i("tag", "buffer = " + buffer);
return buffer; // <-- Here is your file's contents !!!
}
private long getFileSize(FTPClient ftp, String filePath) throws Exception {
long fileSize = 0;
FTPFile[] files = ftp.listFiles(filePath);
if (files.length == 1 && files[0].isFile()) {
fileSize = files[0].getSize();
}
Log.i("tag", "File size = " + fileSize);
return fileSize;
}
}
After have worked on this problem and spent hours, I've found out that the Android Apache retrieveFile() and retrieveFileStream sometimes don't work very well when the FileSize is too big.
Ensure to set the right TypeFile to BinaryFile
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
Also never forget to pass in LocalPassiveMode for download commands
mFTPClient.enterLocalPassiveMode();

Categories

Resources