2012-09-13 239 views
1

在下面的程序中,我得到如下所示的異常。基本上我正在嘗試做的是我從遠程系統複製文件到設備。但是,當保存到存儲卡時在模擬器和設備上,我打了一個異常。下面的例外是來自模擬器,我可以說存儲卡沒有連接到模擬器,所以exception.but將代碼工作的物理設備。Android將文件保存到存儲卡

如何使模擬器上的代碼工作和設備

例外:

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(); 

      } 


    } 
} 

回答

2

這樣做對文件的創建;比你的更好,更安全的方式

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

這對兩者都有效;測試:) –

+0

但我如何將從遠程文件sftpChannel.get()並使用您給定的代碼? – Rajeev

+0

你應該用'file'代替'/ mnt/sdcard/download/dd.txt'在使用我的代碼之後 –