Android将文件保存到存储卡

时间:2012-09-13 10:31:46

标签: java android android-emulator jsch

在下面的程序中,我得到如下所示的异常。基本上我想要做的是我将文件从远程系统复制到设备。但是当在模拟器和设备上保存到存储卡时我我遇到了一个异常。下面的异常来自模拟器,我可以说存储卡没有连接到模拟器,所以异常。但代码适用于物理设备。

如何使代码在模拟器和设备上运行

例外:

 09-13 15:47:16.789: I/System.out(400): java.io.FileNotFoundException: /mnt/sdcard/Download/new.txt (Not a directory)

代码:

package com.scp2;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.jcraft.jsch.*;


import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;

public class Scp2Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

            JSch jsch = new JSch();
            Session session = null;
            try {
                session = jsch.getSession("guest", "17.30.5.2", 22);

                session.connect();
                Toast.makeText(this,  "in try2" , Toast.LENGTH_SHORT).show();

                channel.connect();
                ChannelSftp sftpChannel = (ChannelSftp) channel;
                File ofile = new File(Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DOWNLOADS),"new.txt");
                Toast.makeText(this, ofile.toString() , Toast.LENGTH_SHORT).show();
                                   try {
                    FileOutputStream f = new FileOutputStream(ofile);
                  sftpChannel.get("/root/a.txt","/mnt/sdcard/download/dd.txt");
                  /*OR What shoud the abobe statement be **/
              //sftpChannel.get("/root/a.txt",ofile); or this statement is correct

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                         System.out.println(e.toString());
                }


                sftpChannel.exit();
                session.disconnect();
            } catch (JSchException e) {
                e.printStackTrace(); 

            } catch (SftpException e) {
                e.printStackTrace();

            }


    }
 }

1 个答案:

答案 0 :(得分:2)

为文件创建执行此操作;比你更好更安全的方式

File dir = new File(Environment.getExternalStorageDirectory(),"/Downloads/");
dir.mkdirs();
String strFileName = "dd.html";
File file = new File(dir,strFileName);