关于ftputiljava的信息

博主:adminadmin 2023-03-20 15:57:07 516

今天给各位分享ftputiljava的知识,其中也会对进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

有关java上传和File以及FileInputStream的区别

1:PostUploadInfo的js是页面ai:fileupload标签自动加载的AIFileUpload.js里的方法

这里的ActionDocumentInfo.java注意与FtpUtilPro.java(它的一个upload方法有bug)的对比能

看出后者的bug.

从这个bug要看出File与FileInputStream的区别,File不属于流,它只是用来屏闭不同文件系统,用来统一

描述文件的实体BEAN,new File时给它传入文件名称或是路径,它就会去根据参数查找对应的文件属性然后封装

成实体。用来处理判断该路径是一个文件还是路径,文件或路径的权限,修改时间等等,路径的子路径list等等目录操作。

File不属于文件流,只能代表一个文件或是目录的路径名而已.

而FileInputStream关注的是文件的内容,是用来进行文件读写等操作的二进制流类。大多数情况下,构造FileInputStream

时传递一个File对象做参数,也可以直接传递String的文件路径。

这个容易混淆的问题在FTP时候很容易出现,因为客户端点击浏览本地文件后在上传时在服务器端如果直接把客户端的

文件名称拿到,然后用new File(“文件名称路径”),再用new InputStream(File)来上传到FTP的话,其实就是相当于服务器

端在服务器本地找File(“文件名称路径”),然后往FTP上传,这是错误的。我们希望的是上传客户端的文件,而不是

服务器端的文件,所以这里应该是直接用apache的FileItem.getInputStream的结果直接upload,如下:

InputStream fileIn = item.getInputStream();////如果直接写成这样new FileInputStream(filePath);就会出现在服务器本机找file上传的问题

//可以查看item.getInputStream()最后其实是从memoryOutputStream(内存里记忆的客户端文件流)来取流的句柄的。

以下是正确的实现

[code]

/**上传附件的时候调用

* @param request

* @param response

* @throws Exception

*/

public void doUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {

CustomProperty cp = CustomProperty.getInstance();

try {

//调用apache控件上传文件,返回数组,第一个存放文件对象,第二个存放参数对象

Object obj[] = ApacheUploadTool.getUploadFileInfo(request);

List fileList = (List)obj[0];

Map paras = (Map)obj[1];

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

cp.set("MESSAGE","找不到上传的文件");

return;

}

String aVirtualFileName="";

String newId="";

String newFileName="";

String aFileType ="";

String docSize = "";

String editMode = HttpUtil.getParameter(request, "edit_mode");

String objectId = HttpUtil.getParameter(request, "OBJECT_ID");

String busiType = HttpUtil.getParameter(request, "BUSI_TYPE");

// 陈超调试修改添加的输出

// System.out.println("================"+editMode);

//保存附件信息

for(int i=0;ifileList.size();i++){

FileItem item = (FileItem)fileList.get(i);

//获取文件流、文件名称

String fileName = fixFileName(item.getName());

IDocumentInfoSV idao = CommonService.getIDocumentInfoSV();

docSize = String.valueOf(item.getSize());

String codetype = String.valueOf(StaticValue.CFG_FTP_PATH_CODE);

String ftpPathName = BaseDataCodeAction.getCodeName(codetype, busiType);

if(null==ftpPathName||"".equals(ftpPathName)){

throw new Exception("没有该业务对应的FTP路径配置!");

}

// 陈超调试的注释

// System.out.println("ftpPathName="+ftpPathName);

FtpUtil ftpUtil = new FtpUtil(ftpPathName);

// FtpUtilPro ftpUtil = new FtpUtilPro(ftpPathName);

// 陈超添加的调试输出

// System.out.println("item=="+item);

// System.out.println("item.getInputStream()=="+item.getInputStream());

InputStream fileIn = item.getInputStream();//new FileInputStream(filePath);//如果直接写成这样就会出现在服务器本机找file上传的问题

//可以查看item.getInputStream()最后其实是从memoryOutputStream(内存里记忆的客户端文件流)来取流的句柄的。

//获取新的文件名,判断是否存在

IBODocumentInfoValue[] retValues = CommonService.getIDocumentInfoSV().queryDocumentInfoList(Long.parseLong(busiType), Long.parseLong(objectId));

for(int j=0;jretValues.length;j++){

String docName = retValues[j].getDocumentName();

if(fileName.equals(docName)){

ExceptionUtil.throwBossException(83000015,new String[]{fileName});

}

}

newFileName = fileName;

if(editMode.equals("addNew")){

// 陈超添加的调试输出

// ftpUtil.upload(fileName, fileIn,FtpUtil.BIN);

ftpUtil.upload(fileName, fileIn,FtpUtil.BIN);

}

else if (editMode.equals("modify")) {

// System.out.println("================"+HttpUtil.getParameter(request, "DOCUMENT_ID"));

String oldId = HttpUtil.getParameter(request, "DOCUMENT_ID");

IBODocumentInfoValue acond = new BODocumentInfoBean();

acond.setDocumentId(Long.parseLong(oldId));

// 陈超更改查询STATE为1

acond.setState(1);

IBODocumentInfoValue[] beanValues = idao.getDocumentInfo(acond,"",null);

if(null == beanValues || beanValues.length==0){

throw new Exception("没有文档信息");

}

IBODocumentInfoValue beanValue = beanValues[0];

String oldFileName = beanValue.getDocumentName();

ftpUtil.upload(oldFileName, fileIn,FtpUtil.BIN);

}

if(i==0){

aVirtualFileName = newFileName;

}else{

aVirtualFileName = aVirtualFileName + "," + newFileName;

}

}

cp.set("IsOk","TRUE");

cp.set("MESSAGE", "附件"+aVirtualFileName+"上传成功!");

cp.set("VIRTUAL_FILE_NAME_LIST", aVirtualFileName);

cp.set("DOCUMENT_ID", newId);

cp.set("DOCUMENT_SIZE", docSize);

} catch (Exception ex) {

cp.set("IsOk","FALSE");

cp.set("MESSAGE",StaticValue.SYS_ERROR_INFO);

log.error(ex);

if(!ex.equals("")){

cp.set("MESSAGE",ExceptionUtil.getBossExceptionHint(ex));

}

}finally{

ApacheUploadTool.showFileUploadMsg(response,cp);

}

}

[/code]

附件是自己的ftp实现示例,和一些网上最简单的jsp上传的代码,也最能说明原理

java 实现ftp上传如何创建文件夹?

准备条件:java实现ftp上传用到了commons-net-3.3.jar包

首先建立ftphost连接

public boolean connect(String path, String addr, int port, String username, String password) {

try {

//FTPClient ftp = new FTPHTTPClient(addr, port, username, password);

ftp = new FTPClient();

int reply;

;

System.out.println("连接到:" + addr + ":" + port);

System.out.print();

reply = ;

if (!FTPReply.isPositiveCompletion(reply)) {

;

System.err.println("FTP目标服务器积极拒绝.");

System.exit(1);

return false;

}else{

(username, password);

;

;

;

System.out.println("已连接:" + addr + ":" + port);

return true;

}

} catch (Exception ex) {

ex.printStackTrace();

System.out.println(ex.getMessage());

return false;

}

}

然后再利用ftpclient的makeDirectory方法创建文件夹

public void createDir(String dirname){

try{

;

System.out.println("在目标服务器上成功建立了文件夹: " + dirname);

}catch(Exception ex){

System.out.println(ex.getMessage());

}

}

断开host连接

public void disconnect(){

try {

;

} catch (IOException e) {

e.printStackTrace();

}

}

最后是程序的调用方法

public static void main(String[] args) {

FtpUploadTest ftpupload = new FtpUploadTest();

if(ftpupload.connect("", "172.39.8.x", 20, "administrator", "abc@123")){

ftpupload.createDir("/UPLOAD");

ftpupload.disconnect();

}

}

校验FTP是否能正常连接的Java类

先写一个异常类,如果FTP的用户名或者密码不正确就通过这个异常类抛出异常,代码如下:

FTPException.java

public class FTPException extends Exception {

    private int replyCode = -1;

    public FTPException(String msg) {

        super(msg);

    }

    public FTPException(String msg, String replyCode) {

        super(msg);

        try {

            this.replyCode = Integer.parseInt(replyCode);

        }

        catch (NumberFormatException ex) {

            this.replyCode = -1;

        }

    }

    public int getReplyCode() {

        return replyCode;

    }

}

FtpUtil.java校验类代码如下:

import java.io.*;

import java.net.Socket;

public class FtpUtils {

    static Logger logger = Logger.getLogger(FtpUtils.class);

    public static boolean debugResponsesUtil = false;

    public static PrintWriter printlog = null;

    public static boolean getFtpLogin(String ip, String port, String username, String password){

        boolean flag = false;   //默认FTP未连接

        printlog = new PrintWriter(System.out);

        debugResponsesUtil = true;

        try {

            Socket controlSock = new Socket(ip, Integer.parseInt(port));

            if (controlSock == null) {

                try{

                    throw new IllegalStateException("Failed to set timeout - no control socket");

                } catch (IllegalStateException e) {

                    logger.error(e.getMessage());

                    e.printStackTrace();

                    return flag;

                }

            }

            controlSock.setSoTimeout(0);

            InputStream is = controlSock.getInputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is));

            // output stream

            OutputStream os = controlSock.getOutputStream();

            Writer writer = new OutputStreamWriter(os);

            String replyStr1 = curReadReply(reader);        //第一次调用curReadReply函数

            String replyCodeStr1 = replyStr1.substring(0, 3);

            String replyText1 = replyStr1.substring(4);

            if (replyCodeStr1.equals("220")) {

                debugResponsesUtil = false;

            } else {

                // if unexpected reply, throw an exception

                try {

                    throw new FTPException(replyText1, replyCodeStr1);

                } catch (FTPException e) {

                    logger.error(e.getMessage());

                    e.printStackTrace();

                    return flag;

                }

            }

            if (debugResponsesUtil) {

                printlog.println("--- " + "USER " + username);

            }

            //send it

            writer.write("USER " + username + "\r\n");

            writer.flush();

            String replyStr2 = curReadReply(reader);        //第二次调用curReadReply函数

            String replyCodeStr2 = replyStr2.substring(0, 3);

            String replyText2 = replyStr2.substring(4);

            if (replyCodeStr2.equals("331")) {

                debugResponsesUtil = false;

            } else {

                //if unexpected reply, throw an exception

                try {

                    throw new FTPException(replyText2, replyCodeStr2);

                } catch (FTPException e) {

                    logger.error(e.getMessage());

                    e.printStackTrace();

                    return flag;

                }

            }

            if (debugResponsesUtil) {

                printlog.println("--- " + "PASS " + password);

            }

            //send it

            writer.write("PASS " + password + "\r\n");

            writer.flush();

            String replyStr3 = curReadReply(reader);        //第三次调用curReadReply函数

            String replyCodeStr3 = replyStr3.substring(0, 3);

            String replyText3 = replyStr3.substring(4);

            if (replyCodeStr3.equals("230")) {

                debugResponsesUtil = false;

            } else {

                //if unexpected reply, throw an exception

                try {

                    throw new FTPException(replyText3, replyCodeStr3);

                } catch (FTPException e) {

                    logger.error(e.getMessage());

                    e.printStackTrace();

                    return flag;

                }

            }

            controlSock.setSoTimeout(1000);

            flag = true;   //FTP连接成功

            controlSock.setSoTimeout(10000);

        } catch (IOException e) {

            logger.error(e.getMessage());

            e.printStackTrace();

        }

        return flag;

    }

    private static String curReadReply(BufferedReader reader){

        String firstLine = null;

        try {

            firstLine = reader.readLine();

        } catch (IOException e) {

            logger.error(e.getMessage());

            e.printStackTrace();

        }

        if (firstLine == null || firstLine.length() == 0) {

            try{

                throw new IOException("Unexpected null reply received");

            } catch (IOException e) {

                logger.error(e.getMessage());

                e.printStackTrace();

            }

        }

        StringBuffer reply = new StringBuffer(firstLine);

        if (debugResponsesUtil) {

            printlog.println(reply.toString());

        }

        String replyCode = reply.toString().substring(0, 3);

        //check for multiline response and build up

        //the reply

        if (reply.charAt(3) == '-') {

            boolean complete = false;

            while (!complete) {

                String line = null;

                try {

                    line = reader.readLine();

                } catch (IOException e) {

                    logger.error(e.getMessage());

                    e.printStackTrace();

                }

                if (line == null) {

                    try{

                        throw new IOException("Unexpected null reply received");

                    } catch (IOException e) {

                        logger.error(e.getMessage());

                        e.printStackTrace();

                    }

                }

                if (debugResponsesUtil) {

                    printlog.println(line);

                }

                if (line.length()  3  line.substring(0, 3).equals(replyCode)  line.charAt(3) == ' ') {

                    reply.append(line.substring(3));

                    complete = true;

                } else {  //not the last line

                    reply.append(" ");

                    reply.append(line);

                }

            }  //end while

        }  //end if

        return reply.toString();

    }

}

摘自:iteye博客地址如下:

        

关于ftputiljava和的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。