从Java上传文件到Unix时的FileNotFoundException

时间:2013-06-10 15:32:32

标签: java unix servlets

我正在尝试从java类上传文件到Unix目录,并在上传时获取FileNotFoundException,我看不出是什么问题。要上传文件我正在使用jcraft API,并且在此命令“channelSftp.put(new FileInputStream(f),f.getName())上发生错误; “。文件存在,连接正常,参数(fileName和pathToUpload正在正确传递。错误是因为fileName目录路径没有附加吗?浏览器不允许我用它发送路径,只是文件名。我'如果有人有明确的解决方案,请发布我的代码请在此处发布。示例代码将非常有用。谢谢大家。

public String uploadFile(String fileName, String pathToUpload) throws IOException {
    session = UnixConnect.getInstance();
    String SFTPWORKINGDIR = pathToUpload;
    String result ="File failed to upload";
    String fileName = new File(fileName).getName(); // file is document.pdf 

    Channel channel = null;
    ChannelSftp channelSftp = null;

    try {
        channel = session.openChannel("sftp");
        channel.connect();
        //System.out.println("SFTP connection established");
        channelSftp = (ChannelSftp)channel;
        channelSftp.cd(SFTPWORKINGDIR);

        File f = new File(fileName);
        ////////////////////////////////////////////
        // file not found error in the next line. 
        //////////////////////////////////////////
        channelSftp.put(new FileInputStream(f), f.getName());


        //change mode for uploaded file 
        String fullpath = SFTPWORKINGDIR +  fileName;
        channel=session.openChannel("exec");
        ((ChannelExec)channel).setCommand("chmod 770 " + fullpath);
        channel.setInputStream(null);
        ((ChannelExec)channel).setErrStream(System.err);

        InputStream in=channel.getInputStream();
        channel.connect();

        result = "File " + fileName + " updloaded to directory " + SFTPWORKINGDIR;

    }
    catch (Exception e) {
        System.out.println("Class uploadFile exception: " + e.toString());  
    }
    finally{
         if (channel != null) {
             channel.disconnect();
         }
    }

    return result;
}

堆栈追踪:

     08:42:02,583 ERROR [STDERR] java.io.FileNotFoundException: test.pdf 
        (The system cannot find the file specified) 08:42:02,583 ERROR [STDERR] at 
java.io.FileInputStream.open(Native Method) 08:42:02,584 ERROR [STDERR] at 
    java.io.FileInputStream.<init>(FileInputStream.java:120) 08:42:02,584 ERROR [STDERR] at 
    spt.implement.uploadFile.uploadFile(uploadFile.java:49) 08:42:02,584 ERROR [STDERR] at 
    spt.controller.UploadController.doPost(UploadController.java:35) 08:42:02,584 ERROR 
    [STDERR] at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)

1 个答案:

答案 0 :(得分:0)

以这种方式工作就可以了:

  1. 在正确的位置创建一个空文件,如下例所示;

    channelSftp.put( new ByteArrayInputStream( "".getBytes() ), 'folder/folder/file.txt');

  2. 使用FileOutPutStream写入文件:

    FileOutputStream fos = new FileOutputStream(file);
    byte[] bytes = new byte[1024];
    int length;
    while ((length = is.read(bytes)) >= 0) {
        fos.write(bytes, 0, length);
    }