Android FTP download exception (file not found) - android

I am trying to retrieve a file via FTP but I am getting the following error in LogCat:
java.io.FileNotFoundException :/config.txt (read-only file system)
I have verified that the file exists on the server, and I can read it by double clicking it in a web browser.
Can anyone help please? Here is the code I am using:
FTPClient client = new FTPClient();
FileOutputStream fos = null;
try {
client.connect("xxx.xxx.xxx.xxx");
client.enterLocalPassiveMode();
client.login("user", "pass");
//
// The remote file to be downloaded.
//
String filename = "config.txt";
fos = new FileOutputStream(filename);
//
// Download file from FTP server
//
client.retrieveFile("/" + filename, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}

You cannot save files on the root of the phone. Use Environment.getExternalStorageDirectory()to get an file object of the SD card's directory and save the file there. Maybe create a directory for it. To do that you need the permission android.permission.WRITE_EXTERNAL_STORAGE.
Sample code:
try {
File external = Environment.getExternalStorageDirectory();
String pathTofile = external.getAbsolutePath() + "/config.txt";
FileOutputStream file = new FileOutputStream(pathTofile);
} catch (Exception e) {
e.printStackTrace();
}

You are trying to read the file in, but you have created an OutputStream, you need to create an inputStream and then read the file from that input stream.
Here is a great article, with come code that is very helpful. This should get you headed in the right direction.
http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml
I hope this helps!
Best of luck

Related

Create CSV or TXT file in app and save it to 'download' folder - Android

I searched and tried a lot before asking this.
But all the code that I'm trying is not working.
I want the file to be stored in the download folder and be accessible from the user also if he uninstalls the app.
I also tried using opencsv library. Could you provide a tested way to create a csv or txt file and store to download folder?
Save to to publicDir(Downloads folder) you first need permission.WRITE_EXTERNAL_STORAGE
check docs
Note this won't work without permmissions
private void saveData(){
String csv_data = "";/// your csv data as string;
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
//if you want to create a sub-dir
root = new File(root, "SubDir");
root.mkdir();
// select the name for your file
root = new File(root , "my_csv.csv");
try {
FileOutputStream fout = new FileOutputStream(root);
fout.write(csv_data.getBytes());
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
boolean bool = false;
try {
// try to create the file
bool = root.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
if (bool){
// call the method again
saveData()
}else {
throw new IllegalStateException("Failed to create image file");
}
} catch (IOException e) {
e.printStackTrace();
}
}

Read/Write file in android

try {
PrintStream out = new PrintStream(openFileOutput("OutputFile.txt", MODE_PRIVATE));
str=mIn.getText().toString();
out.println(str);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
i want to ask if this code create file called(OutputFile)?and if yes where is the path of this file??
i want to ask if this code create file called(OutputFile)
it creates a file called OutputFile.txt
and if yes where is the path of this file??
you can retrieve its path using getFileStreamPath, which returns the file created with openFileOutput
File file = getFileStreamPath("OutputFile.txt");
String path = null;
if (file != null) {
path = file.getPath();
}

Android created a file in Android/data/com.mypackage but looks for it in data/data/com.mypackage

This is how I create the file:
File directory = null;
File file = null;
try {
directory = new File(this.getExternalFilesDir(null));
} catch (Exception ex) {
ex.printStackTrace();
if (!directory.exists()) {
directory.mkdirs();
}
}
file = new File(directory, "user_data.json");
if (!file.exists()) {
try {
file.getParentFile().mkdirs();
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
and then this file appears in:
Android/data/com.mypackage.asd/files/user_data.json
but later on when I need it, using this code:
FileInputStream fis = null;
try {
fis = context.openFileInput("user_data.json");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
I get a NullPointerException and I see that the system looks for the file in
data/data/com.mypackage.asd/files/user_data.json
Why does it replace "Android" with "data" in the path?
In the first case, you are using getExternalFilesDir().
In the second case, you are using openFileInput().
Those are not pointing to the same place.
If you want your file to be placed onto external storage, use getExternalFilesDir() everywhere.
If you want your file to be placed onto internal storage, use getFilesDir() and/or openFileInput().

Android: write bytes to image file on SD Card

I'm trying to create an image file on sd-card, building it from the bytes that a server is sending towards me after calling a web-service (basically: download file).
I managed to get "something" on the client-side, and try to write those bytes to a file, using:
FileOutputStream fOut = null;
BufferedOutputStream bOs = null;
try {
fOut = new FileOutputStream(returnedFile);
bOs = new BufferedOutputStream(fOut);
bOs.write(bytesToWrite);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (bOs != null) {
bOs.close();
fOut.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
but the image file is broken (its size is > 0kb, but broken).
I ended up opening that file on my computer with a text editor, and I saw that some of the initial file data (before being sent), differs from the final one. So I'm guessing that there is some kind of encoding misstakening or something like that.
I would appreciate an idea of how to make this work ( download image file from a web server, and open in on my phone).
PS. I can also change or get info about the server configuration, as it was configured by a friend of mine.
PS2. I should be able not to download only images, but any kind of file.
I think It's better you encode the image to Base64 in your server, for example in PHP you can do it like this :
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
And then in android you decode the Base64 string into your image file:
FileOutputStream fos = null;
try {
if (base64ImageData != null) {
fos = context.openFileOutput("imageName.png", Context.MODE_PRIVATE);
byte[] decodedString = android.util.Base64.decode(base64ImageData, android.util.Base64.DEFAULT);
fos.write(decodedString);
fos.flush();
fos.close();
}
} catch (Exception e) {
} finally {
if (fos != null) {
fos = null;
}
}
First of all make sure you have this permissions on your android manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
File stream is designed to work on local file storage rather than network connection. Use URLConnection class instead.
URL uri = new URL("Your Image URL");
URLConnection connection = uri.openConnection();
InputStream stream = connection.getInputStream();
//DO other stuff....

getting file not found exception

I have my android activity :
try {
File root=Environment.getExternalStorageDirectory();
Log.i("root",root.toString());
File dir=new File(root.getAbsolutePath() + "/downloads");
dir.mkdirs();
file=new File(dir,"mytext.txt");
FileOutputStream out=new FileOutputStream(file,true);
PrintWriter pw=new PrintWriter(out);
pw.println("Hello! Welcome");
pw.println("You are Here...!!!");
pw.flush();
pw.close();
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
also added :
<uses-permission android:name="androd.permission.WRITE_EXTERNAL_STORAGE"/>
but it throws me FileNotfound exception :
01-13 09:06:44.442: WARN/System.err(419): java.io.FileNotFoundException: /mnt/sdcard/downloads/mytext.txt (No such file or directory)
and if i add
if(file.exists()){
System.out.println("file exists");
}
else{
System.out.println("No such Fileeeeeeeeee");
}
it moves into "else" part.
Thanks
Sneha
Try this,,it works for me
// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
//now attach OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
GO through this for more details
In Android 6 (Marshmallow) I had to explicitely check whether my app has permission "WRITE_EXTERNAL_STORAGE"
Not sure but please verify that there exists External Storage in your emulator or phone otherwise it will through exception.

Categories

Resources