-1

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();
     }
Kevmeister
  • 147
  • 1
  • 1
  • 12
  • Are you using the same credentials for your app and your FTP test? It's possible the server is presenting different file structures. What do you see in a full-up FTP client like FileZilla? – Basic Jul 25 '12 at 15:38

2 Answers2

0

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();
}
nkr
  • 3,026
  • 7
  • 31
  • 39
  • To be honest, I don't really need to save this file, I only need to read the contents. Is it possible to download the file via FTP, read the contents and then discard the file? – Kevmeister Jul 25 '12 at 16:16
  • You can use a `ByteArrayOutputStream` instead of a `FileOutputStream`. If you are only interested in reading text files you can create a `String` from it. See this question: [Get an OutputStream into a String](http://stackoverflow.com/questions/216894/get-an-outputstream-into-a-string) – nkr Jul 25 '12 at 16:22
0

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

BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156