2012-11-02 37 views

回答

5

在這種情況下,最好只創建並處理錯誤。這種方式的操作是原子的,在SSH的情況下,您還可以節省大量的網絡流量。如果您先進行測試,那麼會出現一個時間窗口,在此期間情況可能會發生變化,您必須處理錯誤結果。

+0

但我可以創建目錄只有一個time.After,當用戶將文件上傳到我們的應用程序到該目錄我要檢查目錄是否爲existed.So,有沒有替代的做到這一點? – SRy

+0

@Srinivas當然,你只能創建一次。之後你會得到一個錯誤。處理它。正如我上面所說。 – EJP

+0

是的,謝謝。我不明白那個縮頭。現在很清楚謝謝。 – SRy

7

這是我如何檢查JSch中的目錄存在。

創建目錄,如果目錄不存在ONT

ChannelSftp channelSftp = (ChannelSftp)channel; 
String currentDirectory=channelSftp.pwd(); 
String dir="abc"; 
SftpATTRS attrs=null; 
try { 
    attrs = channelSftp.stat(currentDirectory+"/"+dir); 
} catch (Exception e) { 
    System.out.println(currentDirectory+"/"+dir+" not found"); 
} 

if (attrs != null) { 
    System.out.println("Directory exists IsDir="+attrs.isDir()); 
} else { 
    System.out.println("Creating dir "+dir); 
    channelSftp.mkdir(dir); 
} 
+0

Af因爲我記得當attrs沒有找到目錄時它不會爲空。它引發一個異常。 – SRy

+0

@SRy:是的,但我已經爲它聲明瞭null,所以如果不拋出異常'attrs'值不爲空 – abi1964

+0

我不認爲你的代碼按照你的預期工作。如果在沒有目錄存在的情況下,當上面的代碼拋出異常時,假設控制權將來到'else'塊,則不會有控制權進入'If-else'塊。所以你的代碼只有在'attrs' not nul – SRy

1

我在這裏重複了同樣的答案在更廣的範圍內。檢查目錄是否存在並創建新目錄的特定行是

  SftpATTRS attrs; 
      try { 
       attrs = channel.stat(localChildFile.getName()); 
      }catch (Exception e) { 
       channel.mkdir(localChildFile.getName()); 
      } 

注意。 localChildFile.getName()是您要檢查的目錄名稱。下面附加了整個類,遞歸地將目錄的文件或內容發送到遠程服務器。

import com.jcraft.jsch.*; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 

import java.io.*; 

/** 
* Created by krishna on 29/03/2016. 
*/ 
public class SftpLoader { 
private static Logger log = LoggerFactory.getLogger(SftpLoader.class.getName()); 

ChannelSftp channel; 
String host; 
int port; 
String userName ; 
String password ; 
String privateKey ; 


public SftpLoader(String host, int port, String userName, String password, String privateKey) throws JSchException { 
    this.host = host; 
    this.port = port; 
    this.userName = userName; 
    this.password = password; 
    this.privateKey = privateKey; 
    channel = connect(); 
} 

private ChannelSftp connect() throws JSchException { 
    log.trace("connecting ..."); 

    JSch jsch = new JSch(); 
    Session session = jsch.getSession(userName,host,port); 
    session.setPassword(password); 
    jsch.addIdentity(privateKey); 
    java.util.Properties config = new java.util.Properties(); 
    config.put("StrictHostKeyChecking", "no"); 
    session.setConfig(config); 
    session.connect(); 
    Channel channel = session.openChannel("sftp"); 
    channel.connect(); 
    log.trace("connected !!!"); 
    return (ChannelSftp)channel; 
} 

public void transferDirToRemote(String localDir, String remoteDir) throws SftpException, FileNotFoundException { 
    log.trace("local dir: " + localDir + ", remote dir: " + remoteDir); 

    File localFile = new File(localDir); 
    channel.cd(remoteDir); 

    // for each file in local dir 
    for (File localChildFile: localFile.listFiles()) { 

     // if file is not dir copy file 
     if (localChildFile.isFile()) { 
      log.trace("file : " + localChildFile.getName()); 
      transferFileToRemote(localChildFile.getAbsolutePath(),remoteDir); 

     } // if file is dir 
     else if(localChildFile.isDirectory()) { 

      // mkdir the remote 
      SftpATTRS attrs; 
      try { 
       attrs = channel.stat(localChildFile.getName()); 
      }catch (Exception e) { 
       channel.mkdir(localChildFile.getName()); 
      } 

      log.trace("dir: " + localChildFile.getName()); 

      // repeat (recursive) 
      transferDirToRemote(localChildFile.getAbsolutePath(), remoteDir + "/" + localChildFile.getName()); 
      channel.cd(".."); 
     } 
    } 

} 

public void transferFileToRemote(String localFile, String remoteDir) throws SftpException, FileNotFoundException { 
    channel.cd(remoteDir); 
    channel.put(new FileInputStream(new File(localFile)), new File(localFile).getName(), ChannelSftp.OVERWRITE); 
} 


public void transferToLocal(String remoteDir, String remoteFile, String localDir) throws SftpException, IOException { 
    channel.cd(remoteDir); 
    byte[] buffer = new byte[1024]; 
    BufferedInputStream bis = new BufferedInputStream(channel.get(remoteFile)); 

    File newFile = new File(localDir); 
    OutputStream os = new FileOutputStream(newFile); 
    BufferedOutputStream bos = new BufferedOutputStream(os); 

    log.trace("writing files ..."); 
    int readCount; 
    while((readCount = bis.read(buffer)) > 0) { 
     bos.write(buffer, 0, readCount); 
    } 
    log.trace("completed !!!"); 
    bis.close(); 
    bos.close(); 
} 
相關問題