×

代码实现文件传输

代码实现文件传输(代码传送)

admin admin 发表于2023-03-29 20:37:11 浏览49 评论0

抢沙发发表评论

本文目录一览:

java代码怎么实现在linux系统上上传文件到windows服务器上

一般linux下传输文件到windows,直接用发ftp就行 ,具体操作1、在windows下,点开始按钮,选:运行,进入DOS

2、在dos下面输入ftp 192.168.1.1(liunx服务器IP地址)然后提示输入,用户名,密码

进入linux服务器的FTP界面,此时输入binary(binary是安全传输方式)

3、此时输入cd /usr(用cd命令切换到相应传输目录)

4输入 get find (要传输的文件)

搞定

仅20行代码,实现文件自动化上传至sftp

最近接到一个产品需求是给指定的 sftp 服务器的指定目录定时推送文件数据。

因为项目组已有现成的组件可以轻松实现 sftp 服务器文件的快速上传,本来是一件很容易的事情,但是问题出现在这个指定的 sftp 服务器所指定的密码带有系统关键字和一些特殊字符,导致现在的组件在解析过程中会失败。 -代码实现文件传输

因此重新开发了下面的这套脚本来满足这个特殊的需求。

Python代码

sftp配置文件代码

(1). yaml 模块

导入 yaml 模块前可以使用以下命令进行模块的安装

yaml 模块在这里的作用是读取 sftp 配置文件代码,将指定key: test_file_upload 下的 key:value 的值转换为字典。

例如:load_config_from_param_conf 函数中的返回值就是使用 yaml 读取到 sftp 配置文件代码后,返回 key: test_file_upload 下配置选项值。 -代码实现文件传输

格式如下:

最后将返回值传给 upload 函数作为参数。

(2). OptionParser 模块

按照 yaml 模块的安装方法,先安装 optparse 模块后,然后在文件中从optparse 中导入 OptionParser 模块

在这里我使用了 OptionParser 这个类实例化了一个对象:opt_parser,通过对象来调用 add_option 方法添加了2个参数,分别是:node, local_file

1). 形参:--node,实参:node

所代表的业务含义是:指定要上传的 sftp 的节点,具体参数值对应 sftp配置文件代码中的 test_file_upload

2). 形参:--local_file,实参:local_file

所代表的业务含义是:指定本地需要被上传到 sftp 服务器的具体文件路径

3). 调用命令

4). add_option()方法

参数:action的枚举

store: 参数列表中带有--node, 那么就会将下一个元素即:test_file_upload 作为其 dest 实参 node 的值; 如果没有--node,那么对应的node的值就为 None; -代码实现文件传输

store_true: 参数列表中有--local_file, 那么其 dest 实参 local_file 的值就为 True; 否者就为 default 定义的默认值,这里没有给定 default 的默认值; -代码实现文件传输

store_false: 参数列表中有--local_file, 那么其 dest 实参 local_file 的值就为 False; 否者就为 default 定义的默认值,这里没有给定 default 的默认值; -代码实现文件传输

参数:type

type是指定传入参数的类型,这里的参数类型为 string 类型。

参数:dest

dest是参数传入后由哪个变量来存储的,后面代码对该参数的引用也是使用这里定义的变量名来引用的。

参数:default

default 是与 action 的值结合使用的。

参数:help

help相当于帮助说明文档,用于描述这个参数的含义。

用C语言实现socket文件传输?

服务端代码:

#include stdio.h

#include stdlib.h

#include errno.h

#include string.h

#include sys/types.h

#include netinet/in.h

#include sys/socket.h

#include sys/wait.h

#define MYPORT 3490 /*定义用户连接端口*/

#define BACKLOG 10 /*多少等待连接控制*/

main()

{

int sockfd, new_fd; /* listen on sock_fd, new connection on new_fd

*/

struct sockaddr_in my_addr; /* my address information */

struct sockaddr_in their_addr; /* connector's address information */

int sin_size;

if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {

perror("socket");

exit(1);

}

my_addr.sin_family = AF_INET; /* host byte order */

my_addr.sin_port = htons(MYPORT); /* short, network byte order */

my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */

bzero((my_addr.sin_zero),; /* zero the rest of the struct */

if (bind(sockfd, (struct sockaddr *)my_addr, sizeof(struct

sockaddr))== -1) {

perror("bind");

exit(1);

}

if (listen(sockfd, BACKLOG) == -1) {

perror("listen");

exit(1);

}

while(1) { /* main accept() loop */

sin_size = sizeof(struct sockaddr_in);

if ((new_fd = accept(sockfd, (struct sockaddr *)their_addr, \

sin_size)) == -1) {

perror("accept");

continue;

}

printf("server: got connection from %s\n", \

inet_ntoa(their_addr.sin_addr));

if (!fork()) { /* this is the child process */

if (send(new_fd, "Hello, world!\n", 14, 0) == -1)

perror("send");

close(new_fd);

exit(0);

}

close(new_fd); /* parent doesn't need this */

while(waitpid(-1,NULL,WNOHANG) 0); /* clean up child processes */

}

}

客户代码:

#include stdio.h

#include stdlib.h

#include errno.h

#include string.h

#include sys/types.h

#include netinet/in.h

#include sys/socket.h

#include sys/wait.h

#define PORT 3490 /* 客户机连接远程主机的端口 */

#define MAXDATASIZE 100 /* 每次可以接收的最大字节 */

int main(int argc, char *argv[])

{

int sockfd, numbytes;

char buf[MAXDATASIZE];

struct hostent *he;

struct sockaddr_in their_addr; /* connector's address information */

if (argc != 2) {

fprintf(stderr,"usage: client hostname\n");

exit(1);

}

if ((he=gethostbyname(argv[1])) == NULL) { /* get the host info */

herror("gethostbyname");

exit(1);

}

if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {

perror("socket");

exit(1);

}

their_addr.sin_family = AF_INET; /* host byte order */

their_addr.sin_port = htons(PORT); /* short, network byte order */

their_addr.sin_addr = *((struct in_addr *)he-h_addr);

bzero((their_addr.sin_zero),; /* zero the rest of the struct */

if (connect(sockfd, (struct sockaddr *)their_addr,sizeof(struct

sockaddr)) == -1) {

perror("connect");

exit(1);

}

if ((numbytes=recv(sockfd, buf, MAXDATASIZE, 0)) == -1) {

perror("recv");

exit(1);

}

buf[numbytes] = '\0';

printf("Received: %s",buf);

close(sockfd);

return 0;

}

用java多线程实现服务器与客户端之间的文件传输的代码!!!急!!!!

程序分Server和Client

服务器端打开侦听的端口,一有客户端连接就创建两个新的线程来负责这个连接

一个负责客户端发送的信息(ClientMsgCollectThread 类),

另一个负责通过该Socket发送数据(ServerMsgSendThread )

Server.java代码如下:

/*

* 创建日期 2009-3-7

*

* TODO 要更改此生成的文件的模板,请转至

* 窗口 - 首选项 - Java - 代码样式 - 代码模板

*/

package faue.MutiUser;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

/**

* 服务器端

*

* @author Faue

*/

public class Server extends ServerSocket {

private static final int SERVER_PORT = 10000;

/**

* 构造方法,用于实现连接的监听

*

* @throws IOException

*/

public Server() throws IOException {

super(SERVER_PORT);

try {

while (true) {

Socket socket = super.accept();

new Thread(new ClientMsgCollectThread(socket), "getAndShow"

+ socket.getPort()).start();

new Thread(new ServerMsgSendThread(socket), "send"

+ socket.getPort()).start();

}

} catch (IOException e) {

e.printStackTrace();

}

}

public static void main(String[] args) throws IOException {

new Server();

}

/**

* 该类用于创建接收客户端发来的信息并显示的线程

*

* @author Faue

* @version 1.0.0

*/

class ClientMsgCollectThread implements Runnable {

private Socket client;

private BufferedReader in;

private StringBuffer inputStringBuffer = new StringBuffer("Hello");

/**

* 得到Socket的输入流

*

* @param s

* @throws IOException

*/

public ClientMsgCollectThread(Socket s) throws IOException {

client = s;

in = new BufferedReader(new InputStreamReader(client

.getInputStream(), "GBK"));

}

public void run() {

try {

while (!client.isClosed()) {

inputStringBuffer.delete(0, inputStringBuffer.length());

inputStringBuffer.append(in.readLine());

System.out.println(getMsg(inputStringBuffer.toString()));

}

} catch (IOException e) {

//e.printStackTrace();

System.out.println(client.toString() + " is closed!");

}

}

/**

* 构造显示的字符串

*

* @param line

* @return

*/

private String getMsg(String line) {

return client.toString() + " says:" + line;

}

}

/**

* 该类用于创建发送数据的线程

*

* @author Faue

* @version 1.0.0

*/

class ServerMsgSendThread implements Runnable {

private Socket client;

private PrintWriter out;

private BufferedReader keyboardInput;

private StringBuffer outputStringBuffer = new StringBuffer("Hello");

/**

* 得到键盘的输入流

*

* @param s

* @throws IOException

*/

public ServerMsgSendThread(Socket s) throws IOException {

client = s;

out = new PrintWriter(client.getOutputStream(), true);

keyboardInput = new BufferedReader(new InputStreamReader(System.in));

}

public void run() {

try {

while (!client.isClosed()) {

outputStringBuffer.delete(0, outputStringBuffer.length());

outputStringBuffer.append(keyboardInput.readLine());

out.println(outputStringBuffer.toString());

}

} catch (IOException e) {

//e.printStackTrace();

System.out.println(client.toString() + " is closed!");

}

}

}

}

客户端:

实现基于IP地址的连接,连接后也创建两个线程来实现信息的发送和接收

/*

* 创建日期 2009-3-7

*

*/

package faue.MutiUser;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.Socket;

/**

* 客户端

*

* @author Faue

*/

public class Client {

private Socket mySocket;

/**

* 创建线程的构造方法

*

* @param IP

* @throws IOException

*/

public Client(String IP) throws IOException {

try {

mySocket = new Socket(IP, 10000);

new Thread(new ServerMsgCollectThread(mySocket), "getAndShow"

+ mySocket.getPort()).start();

new Thread(new ClientMsgSendThread(mySocket), "send"

+ mySocket.getPort()).start();

} catch (IOException e) {

//e.printStackTrace();

System.out.println("Server.IP:" + IP

+ " port:10000 can not be Connected");

}

}

public static void main(String[] args) throws IOException {

try {

new Client(args[0]);

} catch (Exception e) {

System.out.println("输入的IP地址错误");

}

}

/**

* 该类用于创建接收服务端发来的信息并显示的线程

*

* @author Faue

* @version 1.0.0

*/

class ServerMsgCollectThread implements Runnable {

private Socket client;

private BufferedReader in;

private StringBuffer inputStringBuffer = new StringBuffer("Hello");

/**

* 得到Socket的输入流

*

* @param s

* @throws IOException

*/

public ServerMsgCollectThread(Socket s) throws IOException {

client = s;

in = new BufferedReader(new InputStreamReader(client

.getInputStream(), "GBK"));

}

public void run() {

try {

while (!client.isClosed()) {

inputStringBuffer.delete(0, inputStringBuffer.length());

inputStringBuffer.append(in.readLine());

System.out.println(getMsg(inputStringBuffer.toString()));

}

} catch (IOException e) {

//e.printStackTrace();

System.out.println(client.toString() + " is closed!");

System.exit(0);

}

}

/**

* 构造输入字符串

*

* @param line

* @return

*/

private String getMsg(String line) {

return client.toString() + " says:" + line;

}

}

/**

* 该类用于创建发送数据的线程

*

* @author Faue

* @version 1.0.0

*/

class ClientMsgSendThread implements Runnable {

private Socket client;

private PrintWriter out;

private BufferedReader keyboardInput;

private StringBuffer outputStringBuffer = new StringBuffer("Hello");

/**

* 得到键盘的输入流

*

* @param s

* @throws IOException

*/

public ClientMsgSendThread(Socket s) throws IOException {

client = s;

out = new PrintWriter(client.getOutputStream(), true);

keyboardInput = new BufferedReader(new InputStreamReader(System.in));

}

public void run() {

try {

while (!client.isClosed()) {

outputStringBuffer.delete(0, outputStringBuffer.length());

outputStringBuffer.append(keyboardInput.readLine());

out.println(outputStringBuffer.toString());

}

out.println("--- See you, bye! ---");

} catch (IOException e) {

//e.printStackTrace();

System.out.println(client.toString() + " is closed!");

System.exit(0);

}

}

}

}

如果对您有帮助,请记得采纳为满意答案,谢谢!祝您生活愉快!

vaela

java点对点传输文件代码

//在我电脑运行没问题,把E:/EKI.txt传送到D:/EKI.txt你可以换成其它文件

//先运行Server,然后client,共三个class有问题QQ23400262

package ch.socket.file;

import java.io.*;

import java.net.ServerSocket;

import java.net.Socket;

public class Server extends Thread {

public static int port = 6789;

public static String host = "127.0.0.1";

private static ServerSocket server = null;

public void run() {

if (server == null) {

try {

// 1、新建ServerSocket实例

server = new ServerSocket(port);

} catch (IOException e) {

e.printStackTrace();

}

}

System.out.println("服务器启动...");

while (true) {

try {

// 2、访问ServerSocket实例的accept方法取得一个客户端Socket对象

Socket client = server.accept();

if (client == null)

continue;

new SocketConnection(client, "D:\\").start();

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

public static void main(String[] args) {

new Server().start();

}

}

package ch.socket.file;

import java.io.*;

import java.io.IOException;

import java.net.Socket;

import java.net.UnknownHostException;

public class Client {

private Socket client;

private boolean connected;

public boolean isConnected() {

return connected;

}

public void setConnected(boolean connected) {

this.connected = connected;

}

public Client(String host, int port) {

try {

// 1、新建Socket对象

client = new Socket(host, port);

System.out.println("服务器连接成功!");

this.connected = true;

} catch (UnknownHostException e) {

this.connected = false;

close();

} catch (IOException e) {

System.out.println("服务器连接失败!");

this.connected = false;

close();

}

}

/**

* 将文件内容发送出去

*

* @param filepath

* 文件的全路径名

*/

public void sendFile(String filepath) {

DataOutputStream out = null;

DataInputStream reader = null;

try {

if (client == null)

return;

File file = new File(filepath);

reader = new DataInputStream(new BufferedInputStream(

new FileInputStream(file)));

// 2、将文件内容写到Socket的输出流中

out = new DataOutputStream(client.getOutputStream());

out.writeUTF(file.getName()); // 附带文件名

int bufferSize = 2048; // 2K

byte[] buf = new byte[bufferSize];

int read = 0;

while ((read = reader.read(buf)) != -1) {

out.write(buf, 0, read);

}

out.flush();

} catch (IOException ex) {

ex.printStackTrace();

close();

} finally {

try {

reader.close();

out.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

/**

* 关闭Socket

*/

public void close() {

if (client != null) {

try {

client.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

public static void main(String[] args) {

Client client = new Client(Server.host, Server.port);

if (client.isConnected()) {

client.sendFile("E:\\EKI.txt");

client.close();

}

}

}

package ch.socket.file;

import java.net.Socket;

import java.io.*;

public class SocketConnection extends Thread{

private Socket client;

private String filepath;

public SocketConnection(Socket client, String filepath){

this.client = client;

this.filepath = filepath;

}

public void run(){

if(client == null) return;

DataInputStream in = null;

DataOutputStream writer = null;

try{

//3、访问Socket对象的getInputStream方法取得客户端发送过来的数据流

in = new DataInputStream(new BufferedInputStream(client.getInputStream()));

String fileName = in.readUTF(); //取得附带的文件名

if(filepath.endsWith("/") == false filepath.endsWith("\\") == false){

filepath += "\\";

}

filepath += fileName;

//4、将数据流写到文件中

writer = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(new File(filepath))))); -代码实现文件传输

int bufferSize = 2048;

byte[] buf = new byte[bufferSize];

int read = 0;

while((read=in.read(buf)) != -1){

writer.write(buf, 0, read);

}

writer.flush();

System.out.println("数据接收完毕");

}catch(IOException ex){

ex.printStackTrace();

}finally{

try{

in.close();

writer.close();

client.close();

}catch(IOException e){

e.printStackTrace();

}

}

}

}

javaweb 怎么样将本地文件传输到远程服务器

可以通过JDK自带的API实现,如下代码:

package com.cloudpower.util;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import sun.net.TelnetInputStream;

import sun.net.TelnetOutputStream;

import sun.net.;

/**

* Java自带的API对FTP的操作

* @Title:

*/

public class Ftp {

/**

* 本地文件名

*/

private String localfilename;

/**

* 远程文件名

*/

private String remotefilename;

/**

* FTP客户端

*/

private FtpClient ftpClient;

/**

* 服务器连接

* @param ip 服务器IP

* @param port 服务器端口

* @param user 用户名

* @param password 密码

* @param path 服务器路径

* @date 2012-7-11

*/

public void connectServer(String ip, int port, String user,

String password, String path) {

try {

/* ******连接服务器的两种方法*******/

//第一种方法

// ftpClient = new FtpClient();

// ftpClient.openServer(ip, port);

//第二种方法

ftpClient = new FtpClient(ip);

ftpClient.login(user, password);

// 设置成2进制传输

ftpClient.binary();

System.out.println("login success!");

if (path.length() != 0){

//把远程系统上的目录切换到参数path所指定的目录

ftpClient.cd(path);

}

ftpClient.binary();

} catch (IOException ex) {

ex.printStackTrace();

throw new RuntimeException(ex);

}

}

public void closeConnect() {

try {

ftpClient.closeServer();

System.out.println("disconnect success");

} catch (IOException ex) {

System.out.println("not disconnect");

ex.printStackTrace();

throw new RuntimeException(ex);

}

}

public void upload(String localFile, String remoteFile) {

this.localfilename = localFile;

this.remotefilename = remoteFile;

TelnetOutputStream os = null;

FileInputStream is = null;

try {

//将远程文件加入输出流中

os = ftpClient.put(this.remotefilename);

//获取本地文件的输入流

File file_in = new File(this.localfilename);

is = new FileInputStream(file_in);

//创建一个缓冲区

byte[] bytes = new byte[1024];

int c;

while ((c = is.read(bytes)) != -1) {

os.write(bytes, 0, c);

}

System.out.println("upload success");

} catch (IOException ex) {

System.out.println("not upload");

ex.printStackTrace();

throw new RuntimeException(ex);

} finally{

try {

if(is != null){

is.close();

}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if(os != null){

os.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

public void download(String remoteFile, String localFile) {

TelnetInputStream is = null;

FileOutputStream os = null;

try {

//获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。

is = ftpClient.get(remoteFile);

File file_in = new File(localFile);

os = new FileOutputStream(file_in);

byte[] bytes = new byte[1024];

int c;

while ((c = is.read(bytes)) != -1) {

os.write(bytes, 0, c);

}

System.out.println("download success");

} catch (IOException ex) {

System.out.println("not download");

ex.printStackTrace();

throw new RuntimeException(ex);

} finally{

try {

if(is != null){

is.close();

}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if(os != null){

os.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

public static void main(String agrs[]) {

String filepath[] = { "/temp/aa.txt", "/temp/regist.log"};

String localfilepath[] = { "C:\\tmp\\1.txt","C:\\tmp\\2.log"};

Ftp fu = new Ftp();

/*

* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器

*/

fu.connectServer("127.0.0.1", 22, "anonymous", "IEUser@", "/temp");

//下载

for (int i = 0; i filepath.length; i++) {

fu.download(filepath[i], localfilepath[i]);

}

String localfile = "E:\\号码.txt";

String remotefile = "/temp/哈哈.txt";

//上传

fu.upload(localfile, remotefile);

fu.closeConnect();

}

}