简体   繁体   English

如何获取远程linux服务器文件输入流

[英]how to get remote linux server file inputstream

I am trying to read a file which is in the remote linux server. 我正在尝试读取远程linux服务器中的文件。 But I do not know how to get the inputstream of the file using java. 但我不知道如何使用java获取文件的输入流。

How can this be done? 如何才能做到这一点?

Assuming that by " remote linux server " you mean " remote linux shell ", you should use an ssh library like JSch . 假设“ 远程linux服务器 ”是指“ 远程linux shell ”,你应该使用像JSch这样的ssh库。 You can find a file download example here . 您可以在此处找到文件下载示例。

Assuming you have a working connection to the server and access to the file, you can create a File object with the URI of the file: 假设您与服务器有连接并访问该文件,您可以使用该File的URI创建一个File对象:

File f = new File(uri);
FileInputStream fis = new FileInputStream(f);

The URI should be the URI to the file, for example "file://server/path/to/file". URI应该是文件的URI,例如“file:// server / path / to / file”。 See also the Javadoc for File(URI) . 另请参阅Javadoc for File(URI)

Maybe SSHJ can help you? 也许SSHJ可以帮到你? https://github.com/shikhar/sshj https://github.com/shikhar/sshj

Features of the library include: 该图书馆的特色包括:

  • reading known_hosts files for host key verification 读取known_hosts文件以进行主机密钥验证
  • publickey, password and keyboard-interactive authentication publickey,密码和键盘交互式身份验证
  • command, subsystem and shell channels 命令,子系统和shell通道
  • local and remote port forwarding 本地和远程端口转发
  • scp + complete sftp version 0-3 implementation scp +完整的sftp版本0-3实现

It depends on how is the file available. 这取决于文件的可用性。 Is it by HTTP, FTP, SFTP or through a server you wrote yourself ? 是通过HTTP,FTP,SFTP还是通过您自己编写的服务器?

If your want to get the file through HTTP, you can use this : 如果您想通过HTTP获取文件,可以使用:

HttpURLConnection connec = (HttpURLConnection)new URL("http://host/file").openConnection();
if(connec.getResponseCode() != connec.HTTP_OK)
{
    System.err.println("Not OK");
    return;
}
System.out.println("length = " + connec.getContentLength());
System.out.println("Type = " + connec.getContentType());
InputStream in = connec.getInputStream();
//Now you can read the file content with in

There is also Jsch library which is very good for SFTP / SCP 还有Jsch库,非常适合SFTP / SCP

You can use any ssh java lib, as was mentioned in other answers, or mount directory with file as NFS share folder. 您可以使用任何ssh java lib,如其他答案中所述,或使用file作为NFS共享文件夹挂载目录。 After mounting you can use usual java API to acsess file. 安装后,您可以使用通常的Java API来处理文件。

Example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM