sftpjava,sftpjava連接

本文目錄一覽:

java通過sftp上傳大文件,時間長,而且會提示超出GC開銷限制,內存溢出,這種問題怎麼解決

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

request.setCharacterEncoding(“GBK”);

HttpSession session = (HttpSession) request.getSession();

final long MAX_SIZE = 10 * 1024 * 1024;// 設置上傳文件最大為 10M

// 允許上傳的文件格式的列表

final String[] allowedExt = new String[] { “jpg”, “jpeg”, “gif”, “png”,

“JPG”, “bmp”, “BMP” };

response.setContentType(“text/html;charset=gbk”);

// 設置字元編碼為UTF-8, 這樣支持漢字顯示

response.setCharacterEncoding(“GBK”);

String strImageName = (String) session.getAttribute(“strName”);

if (ServletFileUpload.isMultipartContent(request)) {

// 實例化一個硬碟文件工廠,用來配置上傳組件ServletFileUpload

DiskFileItemFactory dfif = new DiskFileItemFactory(); dfif.setSizeThreshold(4096);// 設置上傳文件時用於臨時存放文件的內存大小,這裡是4K.多於的部分將臨時存在硬碟

dfif.setRepository(new File(this.getServletContext().getRealPath(

“/”)

+ “Image”));// 設置存放臨時文件的目錄,web根目錄下的Image目錄

// 用以上工廠實例化上傳組件

ServletFileUpload sfu = new ServletFileUpload(dfif); // 設置最大上傳尺寸

sfu.setSizeMax(MAX_SIZE); PrintWriter out = response.getWriter();

// 從request得到 所有 上傳域的列表

List fileList = null;

try {

fileList = sfu.parseRequest(request);

} catch (FileUploadException e) {// 處理文件尺寸過大異常

if (e instanceof SizeLimitExceededException) {

out.println(“文件尺寸超過規定大小:” + MAX_SIZE + “位元組p /”);

out.println(“a href=’addGoods.jsp’ 返回/a”);

return;

}

e.printStackTrace();

}

// 沒有文件上傳

if (fileList == null || fileList.size() == 0) {

out.println(“請選擇要上傳文件ap /”);

out.println(“a href=’addGoods.jsp’ 返回/a”);

return;

}

// 得到所有上傳的文件

Iterator fileItr = fileList.iterator();

// 循環處理所有文件

this.list = new ArrayList();

while (fileItr.hasNext()) {

long size = 0;

// 得到當前文件

fileItem = (FileItem) fileItr.next();

// 忽略簡單form欄位而不是上傳域的文件域(input type=”text” /等)

if (fileItem == null || fileItem.isFormField()) {

System.out.println(fileItem.getFieldName());

inputstr = fileItem.getString(“GBK”);

list.add(inputstr);

continue;

}

// 得到文件的完整路徑

path = fileItem.getName();

// 得到文件的大小

size = fileItem.getSize();

if (“”.equals(path) || size == 0) {

out.println(“請選擇上傳文件p /”);

out.println(“a href=’addGoods.jsp’ 返回/a”);

return;

}

System.out.println(“文件的完整路徑” + path);

// 得到去除路徑的文件名

t_name = path.substring(path.lastIndexOf(“\\”) + 1);

// 得到文件的擴展名(無擴展名時將得到全名)

String t_ext = t_name.substring(t_name.lastIndexOf(“.”) + 1);

// 拒絕接受規定文件格式之外的文件類型

//System.out.println(“文件名:” + t_name);

//System.out.println(“文件擴展名:”+t_ext);

// System.out.println(t_ext);

int allowFlag = 0;

int allowedExtCount = allowedExt.length;

for (; allowFlag allowedExtCount; allowFlag++) {

if (allowedExt[allowFlag].equals(t_ext))

break;

}

if (allowFlag == allowedExtCount) {

out.println(“請上傳以下類型的文件p /”);

for (allowFlag = 0; allowFlag allowedExtCount; allowFlag++)

out.println(“*.” + allowedExt[allowFlag]

+ ” “);

out.println(“p /a href=’addGoods.jsp’ 返回/a”);

return;

}

long now = System.currentTimeMillis();

// 根據系統時間生成上傳後保存的文件名

u_name = this.getServletContext().getRealPath(“/”)

+ “ImageDown\\” + t_name;

//System.out.println(u_name);

try {

// 保存文件

fileItem.write(new File(u_name));

/*out

.println(“文件上傳成功. 文件大小: ” + size

+ “位元組p /”);

out.println(“圖片上傳成功!”

+ “a href=’addGoods.jsp’ 繼續添加商品/a”);*/

} catch (Exception e) {

e.printStackTrace();

}

}

java向SFTP伺服器上傳文件,如何判斷伺服器上的文件夾是否存在?

如果你的JAVA部署的tomcat,就是你要查找文件的伺服器,那就用:

File file = new File(“文件路徑”)。

如果你本地的JAVA想要訪問遠程的一個伺服器的文件是否存在,就得用如下方法:

URL url = new URL(「文件路徑:可以是本地伺服器的路徑,也可以是遠程伺服器的路徑」)

HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();

//message = urlcon.getHeaderField(0);

//文件存在『HTTP/1.1 200 OK』 文件不存在 『HTTP/1.1 404 Not Found』

Long TotalSize=Long.parseLong(urlcon.getHeaderField(“Content-Length”));

if (TotalSize0){

return true;

}else{

return false;

}

Java是一種可以撰寫跨平台應用軟體的面向對象的程序設計語言。Java 技術具有卓越的通用性、高效性、平台移植性和安全性,廣泛應用於PC、數據中心、遊戲控制台、科學超級計算機、行動電話和互聯網,同時擁有全球最大的開發者專業社群。

java ftp 和 sftp的區別

文件傳送協議FTP(File Transfer Protocol)是TCP/IP協議簇中的一個成員,也是現在網際網路上最廣泛的文件傳送協議。FTP協議包括兩個部分,一個是FTP客戶端,另一個是FTP伺服器。當然,FTP伺服器是用來存儲文件資源的,FTP客戶端通過訪問FTP伺服器來獲得資源的。

安全文件傳送協議SFTP(Secure File Transfer Protocol)可以為文件傳送提供安全的加密/解密技術。基本語法和FTP差不多。SFTP是SSH的一部分,在SSH軟體包中,已經包含了一個SFTP(Secure File Transfer Protocol)的安全文件傳輸子系統,SFTP本身沒有單獨的守護進程,它必須使用sshd守護進程(埠號默認是22)來完成相應的連接操作。由於這種傳輸方式使用了加密/解密技術,文件傳送相對來說是很安全的,但是是有代價的,它的傳輸效率比FTP要低得多。

引自:網頁鏈接

java連接Sftp伺服器後,使用第三方jar com.jcraft.jsch.ChannelSftp;用get()方法獲取的InputStream流為空

java連接Sftp伺服器後,使用第三方jar com.jcraft.jsch.ChannelSftp;用get()方法獲取的InputStream流為空,檢查下第3方初始化這些寫對沒有,或者就是沒得到流,列印看看,解決問題。

java sftp上傳文件 ,在cd時 空指針異常,伺服器上path存在

try {

s;

} catch (SftpException sException) {

if (s == sException.id) {// 如果文件夾不存在,則進行新建

s;

s;

}

}

用這個就可以解決sftp服務目錄不存在問題

sftp免密用java怎麼調用

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

import java.util.Properties;

import java.util.Vector;

import org.apache.commons.lang.ArrayUtils;

import com.huawei.bme.commons.om.log.DebugLog;

import com.huawei.bme.commons.om.log.LogFactory;

import com.huawei.icity.commons.constants.KeyConstant;

import com.huawei.icity.commons.constants.NumberConstant;

import com.huawei.icity.commons.exception.SPMException;

import com.huawei.icity.commons.log.IcityLogFactory;

import com.huawei.icity.commons.log.IcityRuntimeLog;

import com.huawei.icity.commons.sysconfig.StaticInitData;

import com.huawei.icity.commons.utils.StringTools;

import com.huawei.icity.omp.common.util.CommonTools;

import com.huawei.icity.omp.interfaces.hint.constant.TimetaskConstants;

import com.huawei.mdmc.bfm.cms.assist.common.domain.SingleTableModel;

import com.jcraft.jsch.Channel;

import com.jcraft.jsch.ChannelSftp;

import com.jcraft.jsch.ChannelS;

import com.jcraft.jsch.JSch;

import com.jcraft.jsch.JSchException;

import com.jcraft.jsch.Session;

import com.jcraft.jsch.SftpException;

/**

* SFTP公共處理類 〈提供SFTP文件上傳,下載,獲取指定目錄 下文件名集合, 獲取指定目錄 下文件集合等方法

*

* @author mKF75022

* @version iCity Manager V100R002 2012-7-3

* @since iCity Manager V100R002C01

*/

public class SFTPTool

{

/**

* 調測日誌記錄器。

*/

private static final DebugLog DEBUGGER = LogFactory.getDebugLog(SFTPTool.class);

/**

* 運行日誌記錄器。

*/

private static final IcityRuntimeLog RUNTIMELOGGER = IcityLogFactory

.getRuntimeLog(SFTPTool.class);

/**

* Sftp客戶端對象

*/

private ChannelSftp sftp = null;

/**

* SFTP IP地址

*/

private String ip;

/**

* SFTP 埠

*/

private String port;

/**

* SFTP 用戶名

*/

private String userName;

/**

* SFTP 密碼

*/

private String password;

/**

* SFTP上傳模式:BINARY

*/

// private static final int BINARY_FILE_TYPE = 2;

/**

*

* 獲取實例

*

* @return SFTPTool newinstance實例

*

*/

public static SFTPTool getNewInstance()

{

return new SFTPTool();

}

/**

* 初始化連接參數

*

* @param sftpIP

* IP

* @param sftpPort

* 埠

* @param sftpUsername

* 用戶名

* @param sftpPassword

* 密碼

*/

public void init(String sftpIP, String sftpPort, String sftpUsername, String sftpPassword)

{

// 獲取SFTP連接信息

this.ip = sftpIP;

this.port = sftpPort;

this.userName = sftpUsername;

this.password = sftpPassword;

}

/**

* 從SFTP將符合約定命名的文件都下載到本地 .

*

* @param sftpDir

* SFTP伺服器文件存放路徑

* @param locDir

* 本地文件存放路徑

* @param regex

* 指定文件名的格式

* @param needBackup

* 是否需要文件備份(true:是;false:否)

* @param needFullMatch

* 是否要求全局匹配(true:是;false:否)

* @param deleteFtpFile

* the delete ftp file

* @return 下載到本地的文件列表

*/

public ListFile synSFTPFileToLocal(String sftpDir, String locDir, String regex,

boolean needBackup, boolean needFullMatch, boolean deleteFtpFile)

{

ListFile files = new ArrayListFile(KeyConstant.INITIAL_NUMBER);

try

{

this.connect(ip, Integer.parseInt(this.port), userName, password);

// 獲得FTP上文件名稱列表

ListString ftpFileNameList = this.listFiles(sftpDir, regex, needFullMatch);

File localFile = null;

int size = ftpFileNameList.size();

// 根據每個FTP文件名稱創建本地文件。

for (int i = 0; i size; i++)

{

// 下載源文件

localFile = this.download(sftpDir, locDir, ftpFileNameList.get(i), deleteFtpFile);

if (localFile.exists())

{

files.add(localFile);

}

if (needBackup)

{

// 備份源文件生成默認備份文件路徑(據請求文件路徑,生成同級目錄的備份文件夾絕對路徑)

String parentDir = sftpDir.substring(NumberConstant.INT_0,

sftpDir.lastIndexOf(“/”) + 1);

String backupDir = parentDir + TimetaskConstants.DEFAULT_BACKUP_DIRNAME;

boolean bakExists = openDir(backupDir);

if (bakExists)

{

this.uploadFile(backupDir, localFile);

}

else

{

boolean parentExists = openDir(parentDir);

if (parentExists)

{

s;

this.uploadFile(backupDir, localFile);

}

else

{

DEBUGGER.error(“sftp parentDir no exisits “);

}

}

}

}

}

catch (Exception e)

{

DEBUGGER.error(“synSFTPFileToLocal Exception”, e);

}

finally

{

this.disconnect();

}

return files;

}

/**

* 連接sftp伺服器

*

* @param sftpip

* ip地址

* @param sftpport

* 埠

* @param sftpusername

* 用戶名

* @param sftppassword

* 密碼

* @return channelSftp

* @throws SPMException

*/

public ChannelSftp connect(String sftpip, int sftpport, String sftpusername, String sftppassword)

{

sftp = new ChannelSftp();

try

{

JSch jsch = new JSch();

jsch.getSession(sftpusername, sftpip, sftpport);

Session sshSession = jsch.getSession(sftpusername, sftpip, sftpport);

RUNTIMELOGGER.info(“Session created”);

sshSession.setPassword(sftppassword);

Properties sshConfig = new Properties();

sshConfig.put(“StrictHostKeyChecking”, “no”);

sshSession.setConfig(sshConfig);

// 設置超時時間為

sshSession.setTimeout(Integer.parseInt(StaticInitData.getFtpConnectTimeOut())

* NumberConstant.INT_1000);

sshSession.connect();

Channel channel = sshSession.openChannel(“sftp”);

channel.connect();

sftp = (ChannelSftp) channel;

// 設置文件類型

// ftpClient.setFileType(BINARY_FILE_TYPE);

// 與防火牆相關

// ftpClient.enterLocalPassiveMode();

}

catch (JSchException e)

{

DEBUGGER.error(“JSchException : {}”, e);

}

return sftp;

}

// /**

// * 創建指定文件夾

// *

// * @param dirName

// * dirName

// */

// public void mkDir(String dirName)

// {

// try

// {

// s;

// }

// catch (SftpException e)

// {

// DEBUGGER.error(“mkDir Exception : ” + e);

// }

// }

/**

* 創建指定文件夾

*

* @param dirName

* dirName

*/

public void mkDir(String dirName)

{

String[] dirs = dirName.split(“/”);

try

{

String now = s;

for (int i = 0; i dirs.length; i++)

{

boolean dirExists = openDir(dirs[i]);

if (!dirExists)

{

s(dirs[i]);

s(dirs[i]);

}

}

s;

}

catch (SftpException e)

{

DEBUGGER.error(“mkDir Exception : ” + e);

}

}

/**

* 打開指定目錄

*

* @param directory

* directory

* @return 是否打開目錄

*/

public boolean openDir(String directory)

{

try

{

s;

return true;

}

catch (SftpException e)

{

DEBUGGER.error(“openDir Exception : ” + e);

return false;

}

}

原創文章,作者:TKZMO,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/329713.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
TKZMO的頭像TKZMO
上一篇 2025-01-14 18:55
下一篇 2025-01-14 18:55

相關推薦

  • sftpjava – Java 中的 SFTP 庫

    一、概述 sftpjava 是一款免費的 Java SFTP 庫,允許開發人員使用 SFTP 協議在遠程伺服器上上傳、下載和管理文件。該庫包含了許多功能豐富的 API,可以輕鬆地實…

    編程 2025-04-22

發表回復

登錄後才能評論