java如何向服务器传文件,详解Java向服务端发送文件的方法

本文实例为大家分享了Java向服务端发送文件的方法,供大家参考,具体内容如下

/*

*给服务端发送文件,主要是IO流。

*/

import java.io.*;

import java.net.*;

class send2

{

public static void main(String[] args) throws Exception

{

Socket s = new Socket("192.168.33.1",10005);//建立服务

BufferedReader bufr = new BufferedReader(new FileReader("io.java"));//读取IO.JAVA文件

PrintWriter pw = new PrintWriter(s.getOutputStream(),true);//将读到的写入服务端

String line = null;

while((line = bufr.readLine())!=null)

{

pw.println(line);

}

// pw.println("over");//标记结束位置

s.shutdownOutput();

BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream()));//读取服务端返回的数据

String str = bufin.readLine();

System.out.println(str);

bufr.close();

s.close();

}

}

class rece2

{

public static void main(String[] args) throws Exception

{

ServerSocket ss = new ServerSocket(10005);//建立服务

Socket s = ss.accept();//接收数据

BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream()));//读取接收到的数据

PrintWriter out = new PrintWriter(new FileWriter("io2.txt"),true);//写入到IO.TXT文本

String line = null;

while((line = bufin.readLine())!= null)//读一行写入一行

{

// if("over".equals(line))

// break;

out.println(line);

}

PrintWriter pw = new PrintWriter(s.getOutputStream(),true);

pw.println("上传成功!");

out.close();

ss.close();

s.close();

}

}

结果:

18180651b86b4376940512dd8dd48d0b.png

以上就是的全部内容,希望能给大家一个参考,也希望大家多多支持脚本之家。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Java实现SFTP文件输,可以使用JSch库。以下是一个简单的示例代码,演示如何使用JSch实现SFTP上文件到资源服务器: ```java import com.jcraft.jsch.*; public class SFTPUploader { public static void main(String[] args) { String host = "sftp.example.com"; String username = "your-username"; String password = "your-password"; int port = 22; String localFilePath = "/path/to/local/file.txt"; String remoteFilePath = "/path/to/remote/file.txt"; JSch jsch = new JSch(); Session session = null; try { session = jsch.getSession(username, host, port); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(password); session.connect(); ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp"); channelSftp.connect(); channelSftp.put(localFilePath, remoteFilePath); channelSftp.disconnect(); } catch (JSchException | SftpException e) { e.printStackTrace(); } finally { if (session != null) { session.disconnect(); } } } } ``` 在这个示例代码中,`host`是资源服务器的主机名,`username`和`password`是SFTP登录凭据,`port`是SFTP口,默认为22。`localFilePath`是本地文件路径,`remoteFilePath`是远程文件路径。 `JSch`实例用于创建SFTP会话,`Session`实例用于连接到资源服务器。在此示例代码中,我们使用`StrictHostKeyChecking`配置来禁用主机密钥检查。接下来,我们打开一个SFTP通道,并将本地文件到远程服务器。 请注意,如果您需要进行多个文件输,则应该重用单个`Session`和`ChannelSftp`实例,而不是每次输都打开和关闭新的会话和通道。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值