我正在使用JSch程序上傳文件並將其下載到我的SFTP服務器。當我下載文件時,該文件包含垃圾值。包含垃圾值的JSch SFTP文件下載
下面是我寫的代碼:
public ChannelSftp createSession(String sftpUserName, String sftpHost, int sftpPort) {
JSch jsch = new JSch();
Channel channel = null;
ChannelSftp c = null;
String privateKey = "~/.exec/id_rsa";
try {
if (session == null) {
session = jsch.getSession(sftpUserName, sftpHost, sftpPort);
//session.setPassword(sftpPassword);
jsch.addIdentity(privateKey);
session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
}
channel = session.openChannel("sftp");
channel.connect();
c = (ChannelSftp) channel;
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
public Integer downloadFile(ChannelSftp channelSftp, String FileToBeCopied, String folderPath) {
int fileDownloaded = -1;
try {
//channelSftp.cd(folderPath);
OutputStream output = new FileOutputStream("/Users/" + System.getProperty("user.name") + "/Downloads/" + FileToBeCopied);
channelSftp.setFilenameEncoding("UTF-8");
channelSftp.get(FileToBeCopied, output);
fileDownloaded = 0;
} catch (FileNotFoundException e) {
fileDownloaded = 1;
e.printStackTrace();
} catch (SftpException e) {
fileDownloaded = 2;
e.printStackTrace();
} catch (Exception e) {
fileDownloaded = 3;
}
return fileDownloaded;
}
public boolean uploadFiles(ChannelSftp channelSftp, String workingFile, String ftpRemoteDefaultDirectory, String workingDirectory) {
boolean flag = false;
if (workingFile != null) {
if (!workingFile.equalsIgnoreCase("")) {
try {
channelSftp.cd(ftpRemoteDefaultDirectory);
try {
File f = new File(workingDirectory + workingFile);
//channelSftp.setFilenameEncoding("UTF-8");
channelSftp.put(new FileInputStream(f), f.getName());
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
destroySession(channelSftp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return flag;
}
我使用MAC。當我在網上查詢時,有人提到OutputStream
將使用「UTF-8」對文件進行編碼,我們不必再做。
您確定SFTP服務器上的文件實際上是UTF-8編碼嗎? –
是的,它是在UTF-8編碼 – user2727493
如何檢查文件是否使用UTF-8編碼? – user2727493