在Android上使用FTP下载文件

3
这是一个从FTP下载文件的类。
public void run() {

    FTPClient ftpClient = new FTPClient();
    try {

        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        String remoteFile1 = "/WhiteList.txt";
        File downloadFile1 = new File("/data/data/com.prosec/files/WhiteList.txt");

        OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));

        boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
        outputStream1.close();

在我的MainAcitivy中,当我打开我的应用程序(OnCreate())时,我实例化ftp类。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.btn);
    btnDicas = (Button) findViewById(R.id.btnDicas);
    out = (TextView) findViewById(R.id.out);
    listView = (ListView) findViewById(R.id.list);
    new Thread(new ReceiveFTP()).start();// HERE

我在这一行遇到了问题

OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));

记录日志:
03-12 09:06:37.704 7457-7509/? I/System.out: Error: /data/data/com.prosec/files/WhiteList.txt: open failed: ENOENT (No such file or directory)
03-12 09:06:37.704 7457-7509/? W/System.err: java.io.FileNotFoundException: /data/data/com.prosec/files/WhiteList.txt: open failed: ENOENT (No such file or directory)
03-12 09:06:37.704 7457-7509/? W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:456)
03-12 09:06:37.712 7457-7509/? W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
03-12 09:06:37.712 7457-7509/? W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:72)
03-12 09:06:37.712 7457-7509/? W/System.err:     at com.prosec.ReceiveFTP.run(ReceiveFTP.java:43)

如果我关闭了应用程序,然后再次打开,它就可以正常工作。这个错误只会在第一次出现。
1个回答

1
你的问题特别在于下载路径是 "/data/data/com.prosec/files/WhiteList.txt"
请参考此页面有关保存文件的内容。
你可以使用 getFilesDir()getCacheDir() 在内部存储上进行操作:
File file = new File(context.getFilesDir(), filename);

或者使用Environment类将其存储在外部存储器上:

File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);

getfileDir不返回/data/data/myApp相同的目录吗? - Gustavo Rotondo
在getFilesDir()的参考中,它说:“如果调用应用程序被移动到采用存储设备,则返回的路径可能会随时间变化,因此只应持久化相对路径”。 - archived

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接