Java文件传输API

时间:2009-07-03 12:31:28

标签: java file-io

我需要将文件传输到我的网络服务器进行处理,如果可能,我想以通用的方式进行处理。

我需要能够至少从以下协议传输文件(最终要遵循更多):

HTTP
FTP
SCP

我真的希望能够将文件发送到SMTP

所以我的问题是,是否有可用的工具包呢?如果是这样,它必须是开源的,因为这是开源项目的一部分。

如果没有已经执行此操作的工具包,那么构建将处理大多数文件传输的接口的最佳方法是什么?

我考虑过这样的事情:

public interface FileTransfer {
    public void connect(URL url, String userid, String password);
    public void disconnect();
    public void getFile(String sourceFile, File destFile);
    public void putFile(File sourceFile, File destFile);
}

然后是一个工厂,它接受源URL或协议并实例化正确的文件处理程序。

4 个答案:

答案 0 :(得分:6)

Apache commons VFS说明了这个问题,虽然快速检查没有表明它会做SCP或SMTP。 Commons NET执行SMTP,但我不知道您可以获得开箱即用的通用接口。对于SCP,这里有一些可能性。

底线似乎是检查VFS实现并查看它是否适合您,也许您可​​以针对不同的协议进行扩展。如果它不合适,关于您的接口,您可能希望所有远程文件引用都是字符串而不是File对象,特别是表示指向远程位置的URI并告诉您要使用的协议的字符串。 / p>

答案 1 :(得分:2)

我正在处理与您非常相似的问题,我找不到任何开源解决方案,因此我正在尝试自己绘制解决方案。这就是我想出来的。

我认为你应该将inputSources和outputSources表示为不同的东西,比如

public interface Input{
      abstract InputStream getFileInputStream();
      abstract String getStreamId();
}
//You can have differen implementation of this interface (1 for ftp, 1 for local files, 1 for Blob on db etc)  

public interface Output{
      abstract OutputStream getOutputStream();
      abstract String getStreamId();
}
//You can have differen implementation of this interface (1 for ftp, 1 for local files, 1 for mailing the file etc)  

然后你应该有一个运动来描述哪个输入应该输出到哪个输出。

 class Movement{
        String inputId;
        String outputId;
 }

描述要制作的动作列表的类。

class MovementDescriptor{
       public addMovement(Movement a);
       public Movement[] getAllMovements();
}  

然后是一个自己完成工作的课程。

class FileMover{

      HashMap<String,Input> inputRegistry;
      HashMap<String,Output> outputRegistry;

      addInputToRegistry(Input a ){
          inputRegistry.put(a.getId(),a);
      }
     addOutputToRegistry(Output a){
          outputRegistry.put(a.getId(),a);
      }

     transferFiles(MovementDescriptor movementDescriptor){

         Movement[] movements =movementDescriptor.getAllMovements();
         foreach (Movement movement: movements){
              //get the input Id
              //find it in the registry and retrieve the associated InputStream
              //get the output Id
              //find it in the registry and retrieve the associated OutputStream
              //copy the stream from the input to the output (you may want to use a temporary file in between)
          }
     }
}

使用它的代码将按如下方式运行:

FileMover fm=new FileMover();

//Register your sources and your destinations
fm.addInputToRegistry(input);
fm.addOutputToRegistry(output)

// each time you have to make a movement create a MovementDescriptor and call
fm.transferFiles(movementDescriptor)

如果您想通过邮件交换我们对该主题的看法,请发送电子邮件至(我的昵称)@gmail dot com。

注意:代码只是草图: - )

答案 2 :(得分:0)

我认为JSch实现了SCP,因此覆盖了那个。

答案 3 :(得分:0)

请使用JCraft。打开“sftp”频道并试试。