Android FTP download exception (file not found)

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

链接地址: http://www.djcxy.com/p/78458.html

上一篇: 简单的方法将Java InputStream的内容写入OutputStream

下一篇: Android FTP下载异常(找不到文件)