我正在尝试按照教程here
中的指示使用SFTP从远程服务器下载文件在InputStream期间,一切似乎都很好,但当它到达OutputStream时,它会崩溃并给我一个跟踪错误:
java.io.FileNotFoundException:/ Internal Storage / Documents / sample.txt: 打开失败:ENOENT(没有这样的文件或目录)
引起: libcore.io.ErrnoException:open failed:ENOENT(没有这样的文件或 目录)
任何帮助?
这是我的代码:
public class MainActivity extends Activity {
private static final String SFTPWORKINGDIR = "/path/to/file";
private String user = "username";
private String pass = "password";
private String host = "hostname";
private int portNum = 22;
private String fileName = "sample.txt";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTask<Void, Void, List<String>>() {
@Override
protected List<String> doInBackground(Void... params) {
try {
Downloader(fileName);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
public void Downloader(String fileName) {
JSch jsch = new JSch();
Session session = null;
Channel channel = null;
ChannelSftp sftpChannel = null;
try {
session = jsch.getSession(user, host, portNum);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(pass);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
sftpChannel = (ChannelSftp) channel;
sftpChannel.cd(SFTPWORKINGDIR); //cd to dir that contains file
try {
byte[] buffer = new byte[1024];
BufferedInputStream bis = new BufferedInputStream(sftpChannel.get(fileName));
File newFile = new File("some/file/");
OutputStream os = new FileOutputStream(newFile); //CRASHES HERE
BufferedOutputStream bos = new BufferedOutputStream(os);
int readCount;
while( (readCount = bis.read(buffer)) > 0) {
Log.d("Downloading", " " + fileName );
bos.write(buffer, 0, readCount);
}
bis.close();
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d( " ", fileName + " has been downloaded. MAYBE");
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
我想我可能已经通过指定外部存储来修复它:
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS);
File newFile = new File(path, "/" + fileName);