Java远程传输文件(增加覆盖取消等功能)

合集下载

java sftp 常用方法

java sftp 常用方法

一、介绍随着信息化时代的到来,数据传输变得越来越重要。

在企业中,有时候需要通过网络将数据从一个服务器传输到另一个服务器。

而其中一种常用的数据传输协议就是SFTP(Secure File Transfer Protocol)。

SFTP是一种基于SSH协议的安全文件传输协议。

它提供了一种安全的通信渠道以及文件传输功能,能够有效地保护传输的数据安全。

在Java中,我们可以通过一些常用的方法来实现SFTP的文件传输,本文将介绍一些Java中SFTP常用的方法。

二、建立SFTP连接在Java中,我们可以使用JSch库来建立SFTP连接。

需要在项目中导入JSch库的jar包。

我们可以通过以下方法来建立SFTP连接:1. 创建JSch对象我们可以通过new JSch()来创建一个JSch对象,用于后续的SFTP连接。

2. 建立Session使用JSch对象的getSession方法建立一个Session对象,需要传入用户名、主机位置区域和端口号等参数,并通过setPassword或setPrivateKey方法设置认证方式。

3. 打开Channel在建立Session之后,可以通过Session对象的openChannel方法打开一个Channel,类型为" sftp"。

4. 建立SFTP连接使用ChannelSftp的connect方法来建立SFTP连接。

以上即为建立SFTP连接的步骤,通过这些方法,我们可以在Java中轻松地实现SFTP连接的功能。

三、上传文件一旦建立了SFTP连接,我们就可以进行文件的上传操作了。

通过以下方法可以实现文件的上传:1. 使用put方法在ChannelSftp对象中,可以使用put方法来上传文件。

需要传入本地文件路径和远程文件路径两个参数。

2. 设置传输模式在上传文件之前,可以通过ChannelSftp对象的setmode方法来设置传输模式,常用的传输模式包括OVERWRITE、RESUME等。

java的远程登录和文件传输功能的实现

java的远程登录和文件传输功能的实现

基于java的远程登录和文件传输功能的实现摘要Internet发展至今产生了两种比较重要的网络体系结构:ISO/OSI和TCP/IP参考模型,ISO/OSI模型有7层:物理层,数据链路层,网络层,传输层,会话层,表示层,应用层。

而TCP/IP模型只有4层:主机至网络层,互连网层,传输层,应用层。

其中TCP/IP 参考模型中的应用层包含所有的高层协议,最早引入的是虚拟终端协议,文件传输协议和电子邮件协议。

本文对网络计算机相互通信的机理进行比较细致和深入的分析,并采用java编程工具实现了远程登录和文件传输的功能。

关键词:TCP/IP JAVA 远程登录文件传输AbstractInternet produces two kinds of more important network system structure so far that Internet is developed, ISO/OSI and TCP/IP consult models, ISO/OSI model is 7 layers: Physics layer, data link layer, network layer, transport layer, session layer, persentaltion layer, opplication layer. And TCP/IP model is 4 layers: From host computer to Internet, network layer, transport layer, opplication layer. TCP/IP among them consult application layer of model include all on the senior level Protocol, introduce TELecommunications NETwork , File Transfer Protocol and Simple Mail Transfer Protocol, Careful and deep analysis that this text compares mechanism that the network computer communicates each other, and adopt java programming tool to realize the functions of telecommunications network and file transfer.KEY WORDS: TCP/IP JA V A TELNET FTP目录前言--------------------------------------------------------------------------------------------1 第一章互联网概述---------------------------------------------------------------------- 3 1.1 互联网的发展状况--------------------------------------------------------------------3 1.2 互联网的应用-------------------------------------------------------------------------5第二章互联网中两种重要的参考模型-----------------------------------------------6 2.1 OSI参考模型-------------------------------------------------------------------------6 2.2 TCP/IP参考模型--------------------------------------------------------------------8第3章远程登录的功能实现----------------------------------------------------------------9 3.1 虚拟终端-------------------------------------------------------------------------------9 3.2 远程登录协议 --------------------------------------------------------------------------11 3.3 有关远程登录的实现方法(线程的概念)---------------------------------------13 3.4 远程登录的最终完成---------------------------------------------------------------18 第4章文件传输的执行行为和功能------------------------------------------------------27 4.1传输文件--------------------------------------------------------------------------------27 4.2 文件传输的传输模式----------------------------------------------------------------28 4.3 构造控制连接和数据连接------------------------------------------------------------32 4.4 文件传输程序的完成-----------------------------------------------------------------42 第5章总结----------------------------------------------------------------------------------53 参考文献---------------------------------------------------------------------------------------54 谢辞----------------------------------------------------------------------------------------55前言历史的发展表明I n t e r n e t的产生要追溯到最开始的时间,穴壁上的画、烟信号、驿站—所有这些通信方式都使我们的祖先一直在考虑一个更好的通信方式。

java传输文件 方案

java传输文件 方案

Java传输文件方案1. 简介在开发Java应用程序时,经常需要通过网络传输文件。

本文将介绍几种常见的Java传输文件的方案,包括使用原生Java API实现文件传输、使用FTP协议传输文件以及使用HTTP协议传输文件。

2. 使用原生Java API实现文件传输Java提供了一系列的API来处理文件传输操作。

下面将介绍如何使用原生Java API实现文件传输。

2.1 文件上传在Java中,可以使用java.io包提供的类来实现文件上传。

以下是一个简单的文件上传示例:import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;import .Socket;public class FileUploader {public static void uploadFile(File file, String host, int port) thr ows IOException {try (Socket socket = new Socket(host, port);FileInputStream fileInputStream = new FileInputStream(fil e);OutputStream outputStream = socket.getOutputStream()) { byte[] buffer = new byte[4096];int bytesRead;while ((bytesRead = fileInputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, bytesRead);}}}}在上述示例中,我们使用Socket类实现了与服务器建立连接,并使用FileInputStream读取文件内容,并通过OutputStream将文件内容写入到服务器。

计算机程序设计员实操考核远程控制题目

计算机程序设计员实操考核远程控制题目

计算机程序设计员实操考核远程控制题目1. 背景远程控制是计算机程序设计员在实际工作中经常遇到的情况之一。

无论是在服务器管理、系统维护还是软件调试和故障排查等方面,远程控制都扮演着重要的角色。

因此,在计算机程序设计员的实操考核中,远程控制题目是必不可少的一部分。

2. 题目要求在本题中,考察的是计算机程序设计员在远程控制方面的实际操作能力。

具体要求如下:1.实现一个简单的远程控制程序,可以通过网络连接远程控制一台虚拟机。

2.程序需要支持以下操作:•连接虚拟机:通过输入虚拟机的IP地址和端口号,建立与虚拟机的网络连接。

•发送命令:可以向虚拟机发送命令,并获取命令的执行结果。

•文件传输:可以向虚拟机发送文件,并在虚拟机上进行保存。

3.提供适当的用户界面,使用户可以方便地进行远程控制操作。

4.实现的程序需要具备一定的安全性,包括对连接的认证和加密等安全措施。

3. 实现思路为了完成上述题目要求,我们可以采取以下实现思路:1.选择合适的编程语言和开发环境。

根据自己的熟悉程度和实际需求,选择一种合适的编程语言和开发环境。

常见的选择包括Python、Java、C#等。

2.理解远程控制的基本原理和相关技术。

了解远程控制的基本原理,并学习相关技术和工具,如TCP/IP、SSH、Telnet等。

3.设计程序的结构和功能。

4.实现程序的各个功能模块,包括建立连接、发送命令和文件传输等。

5.编写用户界面,提供友好的操作界面。

6.添加安全性措施,包括连接认证和加密等。

7.进行测试和调试,确保程序的可靠性和稳定性。

8.完善文档,包括项目介绍、使用说明和开发文档等。

4. 参考资源在实现过程中,可以参考以下资源:•官方文档:参考相应编程语言和开发环境的官方文档,了解相关函数和类的使用方法。

•在线教程:通过搜索引擎找到相关的在线教程和示例代码,学习相关知识和技巧。

•开源项目:寻找开源的远程控制软件或类库,学习其实现思路和代码实现方式。

【Java】后台将文件上传至远程服务器

【Java】后台将文件上传至远程服务器

【Java】后台将⽂件上传⾄远程服务器问题:由于系统在局域⽹(能访问外⽹)内,但外⽹⽆法请求局域⽹内服务器⽂件和进⾏处理⽂件。

解决:建⽴⽂件服务器,⽤于存储⽂件及外⽹调⽤。

客户端(⽂件上传):package cn.hkwl.lm.util;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import .HttpURLConnection;import .MalformedURLException;import .URL;import java.util.Iterator;import java.util.Map;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.mime.FormBodyPart;import org.apache.http.entity.mime.MultipartEntity;import org.apache.http.entity.mime.content.FileBody;import org.apache.http.entity.mime.content.StringBody;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class UploadToServer {private static final Logger log = LoggerFactory.getLogger(UploadToServer.class);public static String postFile(String url,Map<String, Object> param, File file) throws ClientProtocolException, IOException {String res = null;CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httppost = new HttpPost(url);httppost.setEntity(getMutipartEntry(param,file));CloseableHttpResponse response = httpClient.execute(httppost);HttpEntity entity = response.getEntity();if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {res = EntityUtils.toString(entity, "UTF-8");response.close();} else {res = EntityUtils.toString(entity, "UTF-8");response.close();throw new IllegalArgumentException(res);}return res;}private static MultipartEntity getMutipartEntry(Map<String, Object> param, File file) throws UnsupportedEncodingException { if (file == null) {throw new IllegalArgumentException("⽂件不能为空");}FileBody fileBody = new FileBody(file);FormBodyPart filePart = new FormBodyPart("file", fileBody);MultipartEntity multipartEntity = new MultipartEntity();multipartEntity.addPart(filePart);Iterator<String> iterator = param.keySet().iterator();while (iterator.hasNext()) {String key = iterator.next();FormBodyPart field = new FormBodyPart(key, new StringBody((String) param.get(key)));multipartEntity.addPart(field);}return multipartEntity;}}服务器端(⽂件接收):package cn.hkwl.office.action;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.io.UnsupportedEncodingException;import java.util.Date;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Random;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONObject;import mons.fileupload.FileItem;import mons.fileupload.disk.DiskFileItemFactory;import mons.fileupload.servlet.ServletFileUpload;import org.apache.jasper.tagplugins.jstl.core.Out;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;import monsMultipartResolver;import cn.zy.action.BaseAction;@Controller@RequestMapping("/file")public class FileAction extends BaseAction {/****/private static final long serialVersionUID = -5865227624891447594L;@RequestMapping("/receive")public @ResponseBody void receive(HttpServletRequest request,HttpServletResponse response) throws Exception {JSONObject json=new JSONObject();// 将当前上下⽂初始化给 CommonsMutipartResolver (多部分解析器)CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());// 检查form中是否有enctype="multipart/form-data"if (multipartResolver.isMultipart(request)) {// 将request变成多部分requestMultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;// 获取multiRequest 中所有的⽂件名Iterator<String> iter = multiRequest.getFileNames();// 定义绝对路径String localPath = getRealPath("/upload/lm");File path = new File(localPath);// ⽂件夹不存在则创建⽂件夹if (!path.exists()) {path.mkdir();}while (iter.hasNext()) {// ⼀次遍历所有⽂件MultipartFile file = multiRequest.getFile(iter.next().toString());if (file != null) {String filepath = localPath +File.separator+ file.getOriginalFilename();// 上传file.transferTo(new File(filepath));// ⽂件数据存储起来json.put("success", true);json.put("httpUrl", "http://serverhostip:9080/lmoffice/upload/lm/"+file.getOriginalFilename()); }}}else{json.put("success", false);}outJson(json);}}应⽤使⽤:private String getHttpUrl(String savePath) throws ClientProtocolException, IOException{File file=new File(getRealPath(savePath));System.out.println(file.exists());Map<String,Object> param=new HashMap<String, Object>();String res=UploadToServer.postFile("http://serverhostip:9080/lmoffice/file/receive",param,file); JSONObject result=JSONObject.fromObject(res);if(result.getBoolean("success")){file.delete();//删除本地⽂件return result.getString("httpUrl");}return "";}/**** 管线迁移公告** @param landId*/@RequestMapping("/gxqygg.do")public @ResponseBodyvoid createGXQYGG(Long landId) {JSONObject json = new JSONObject();Land land = landService.getLandInfo(landId);Map<String, Object> map = new HashMap<String, Object>();map.put("land", land);Calendar calendar = Calendar.getInstance();// 取当前⽇期。

Java远程传输文件(增加覆盖取消等功能)

Java远程传输文件(增加覆盖取消等功能)

发送端/ *by小郭*远程文件传输**/import javax.swing.*;import .*;import java.io.*;import java.awt.*;import ng.*;import java.awt.event.*;public class TcpSend extends JFrame implements ActionListener {private JButton button;private JFileChooser chooser;//private FileInputStream in;//private String filename;//byte[] by=new byte[100000];public TcpSend(){super("小郭文件传输发送端");this.setBounds(10,10,400,400);this.setLayout(null);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setResizable(false);this.setVisible(true);chooser=new JFileChooser();button=new JButton("发送");button.setFont(new Font("楷体",Font.PLAIN,30));button.setBounds(0,0,400,400);add(button);button.addActionListener(this);}public void actionPerformed(ActionEvent e){chooser.showOpenDialog(this);if(chooser.showOpenDialog(this)==JFileChooser.CANCEL_OPTION) {button.setText("取消文件发送");//小bug 按2次才能取消return;}Send send=new Send(chooser.getSelectedFile());send.start();button.setText("文件已发送");}public static void main(String[] args){new TcpSend();}}//end TcpSendclass Send extends Thread{private File file;private Socket socket;private DataOutputStream Dout;private DataInputStream Din;BufferedInputStream buffered;Send(File file){this.file = file;try{socket= new Socket("localhost",1111);//localhost可以改成IP 如果是内网直接填内网IP 外网的话IP要映射buffered=new BufferedInputStream(socket.getInputStream());//创建一个缓冲区数组,保存套接字s输入流,以便使用Din = new DataInputStream(buffered);//数据输入流,用来读取Dout = new DataOutputStream(socket.getOutputStream());//数据输出流,用来写入由数据输入流读取的数据} catch (IOException e) {e.printStackTrace();}}public void run(){try{Dout.writeUTF(file.getName());//将文件名写入输出流JOptionPane.showMessageDialog(null,"发送的文件是:"+file.getName());boolean isAccepted = Din.readBoolean();//接收端是否读取输入字节if(isAccepted){// JOptionPane.showMessageDialog(null,"对方已经接受文件传输,点击确定开始传输!");BufferedInputStream Bin = new BufferedInputStream(new FileInputStream(file));//创建一个缓冲区数组,保存文件输入流byte[] by = new byte[100000];int l;while(( l =Bin.read(by))!= -1)//从输入流中将各字节读取到by数组中只要不是=-1 如果=-1即到达流末尾就跳出循环{Dout.write(by,0,l);//将by数组中从偏移地址0开始的1个字节写入输出流。

java网络文件传输的实现

java网络文件传输的实现

java网络文件传输的实现——Socket编程本程序分为服务器和客户端两个小程序。

主要实现的功能是:客户端向服务器端请求一个文件的传输连接,服务器接收到请求命令后,要求客户端发送用户名和密码,如果正确,就执行传输文件的过程,客户端接收完后,保存到一个文件中并在屏幕上显示出来。

设计原理:服务器端建立一个SocketServer等待客户端的连接,每来一个客户端的请求连接,就创建一个新的线程对其进行单独服务,然后继续等待其他的客户端的连接。

客户端向服务器发送文件传输请求,在服务器端要求鉴权时,输入用户名和密码发送给服务器验证,如果验证通过就开始文件传输。

使用方法,如果需要重新编译的话输入以下两条命令:javac SendFileSocket.javajavac SendFileClient.java在命令行下的运行方式:服务器端:java SendFileSocket客户端:java SendFileClient serverIPAddress例如:java SendFileClient 192.168.0.153服务器程序:public class SendFileSocket extends Thread{/*** @param args*/public static void main(String[] args ){/*if ( args.length > 0 ) // 如果有参数输入就启动服务器程序 {server( );} else{// 否则启动客户端进程client( );}*/server();//启动服务器程序}private static final int PORT= 6000;private Socket s;private static final String name="zieckey";private static final String password ="123456";public SendFileSocket(Socket s ){this.s = s;}public void run(){try{OutputStream os = s.getOutputStream();InputStream is = s.getInputStream();os.write("Hello,welcome you!".getBytes());byte[] buf =new byte[100];while( true ){int len = is.read( buf );String revStr =new String( buf, 0, len );System.out.println("This client wants to "+revStr );String fileName;if( revStr.startsWith("get "))//表明客户端请求传输一个文件{os.write("Please input your name and password! Using the format:name@password".getBytes());fileName =getFileName( revStr );len = is.read( buf );revStr =new String( buf, 0, len );System.out.println("The received user name and password:"+revStr);if( revStr.startsWith("zieckey@123456")){FileInputStream fins =new FileInputStream( fileName );//byte[] fielBuf = new byte[100];int data;while(-1 !=( data = fins.read()))//从文件中读取数据,每次读取1字节{os.write( data );//将读取到的数据写到网络数据流中发送给客户段}break;}}else{os.write("geting file's usage is:get filename".getBytes());}}os.close();is.close();s.close();}catch(Exception e ){e.printStackTrace();}}/** 作用:从客户端发来了文件请求命令中提取出所请求的文件名 * 参数:客户端发来了文件请求命令字符串,应该以“get ”开头 * 返回值:提取出所请求的文件名*/private String getFileName(String revStr ){String fileName;fileName = revStr.substring( 3 );while( fileName.startsWith(" ")){fileName = fileName.substring( 1 );}return fileName;}public static void server(){System.out.println("This is server");try{ServerSocket ss =new ServerSocket(PORT);int count= 0;while( true ){// 创建一个Socket等待客户端连接Socket s = ss.accept();count++;System.out.println("This is the "+count+"'st client connetion!");new SendFileSocket( s ).start();// 启动一个线程为这个客户端服务}}catch(Exception ex ){ex.printStackTrace();}}/*public static void client(){System.out.println( "This is client" );try{// 创建一个SocketSocket s = new Socket( InetAddress.getByName( null ), PORT );OutputStream os = s.getOutputStream( );// 输出流InputStream is = s.getInputStream( );// 输入流byte[] buf = new byte[100];int len = is.read( buf );// 从输入流中读取数据到bufSystem.out.println( new String( buf, 0, len ) );// 向输出流中写入数据,请求传输一个文件os.write( "get server.txt".getBytes( ) );len = is.read( buf );// 从输入流中读取数据到bufString tempStr = new String(buf,0,len);if ( tempStr.startsWith( "Please input your name and password" ) ){System.out.print("Please input your name and password, ");System.out.print("Using the format:name@password:");System.in.read( buf );os.write( buf );}//开始读取文件数据并把它写到一个名为"clientread.txt"的文件中FileOutputStream fos = new FileOutputStream( "clientread.txt" ); int data;while ( -1 != ( data = is.read( ) ) ){fos.write( data );}System.out.println("\nFile has been recerved successfully.");os.close( );is.close( );s.close( );} catch ( Exception ex ){ex.printStackTrace( );}}*/}客户端程序:import .InetAddress;import .InetSocketAddress;import .Socket;public class SendFileClient{private static final int Server_PORT = 6000;private static final int Client_PORT = 6001;/*** 使用方法:运行这个程序需要带上参数,参数类型为点分十进制的ip地址,例如:192.168.0.153* @param args* @throws IOException*/public static void main(String[] args )throws IOException{// TODO Auto-generated method stubSystem.out.println("This is client");/*System.out.print("Please input your name and password, ");System.out.print("Using the format:name@password:");byte[] buf = new byte[100];System.in.read( buf );*/byte[] buf =new byte[100];byte[]name=new byte[100];//InetAddress inetAddr;if(!isIPAddress(args[0])){System.out.println("The usage is : java SendFileClient ipaddress");System.out.println("For example : java SendFileClient 192.168.0.153");return;}String ipStr = args[0];try{// 创建一个SocketSocket s =new Socket();s.connect(new InetSocketAddress(ipStr , Server_PORT ), Client_PORT );OutputStream os = s.getOutputStream();// 输出流InputStream is = s.getInputStream();// 输入流int len = is.read( buf );// 从输入流中读取数据到bufSystem.out.println(new String( buf, 0, len ));// 向输出流中写入数据,请求传输一个文件os.write("get server.txt".getBytes());len = is.read( buf );// 从输入流中读取数据到bufString tempStr =new String(buf,0,len);if( tempStr.startsWith("Please input your name and password")){System.out.println("Please input your name and password, ");System.out.println("Using the format:name@password:");do{System.in.read(name);}while(name.length<5 );os.write(name);}//开始读取文件数据并把它写到一个名为"clientread.txt"的文件中FileOutputStream fos =new FileOutputStream("clientread.txt");int data;while(-1 !=( data = is.read())){fos.write( data );}System.out.println("\nFile has been recerved successfully.");os.close();is.close();s.close();}catch(Exception ex ){ex.printStackTrace();}。

java实现两台电脑间TCP协议文件传输

java实现两台电脑间TCP协议文件传输

java实现两台电脑间TCP协议⽂件传输记录下之前所做的客户端向服务端发送⽂件的⼩项⽬,总结下学习到的⼀些⽅法与思路。

注:本⽂参考⾃《⿊马程序员》视频。

⾸先明确需求,在同⼀局域⽹下的机器⼈A想给喜欢了很久的机器⼈B发送情书,但是机器⼈B事先并不知道⼩A的⼼思,那么作为⽉⽼(红娘)该如何帮助他们呢?然后建⽴模型并拆分需求。

这⾥两台主机使⽤⽹线直连,在物理层上确保建⽴了连接,接下来便是利⽤相应的协议将信息从电脑A传给电脑B。

在这⼀步上,可以将此过程抽象为⽹络+I/O(Input、Output)的过程。

如果能在⼀台电脑上实现⽂件之间的传输,再加上相互的⽹络协议,羞涩的A不就可以将情书发送给B了吗?因此要先解决在⼀台电脑上传输信息的问题。

为了在⽹络上传输,使⽤必要的协议是必要的,TCP/IP协议簇就是为了解决计算机间通信⽽⽣,⽽这⾥主要⽤到UDP和TCP两种协议。

当⼩A可以向⼩B发送情书后,⼜出现了众多的追求者,那么⼩B如何去处理这么多的并发任务呢?这时便要⽤到多线程的技术。

因此接下来将分别介绍此过程中所⽤到了I/O流(最基础)、⽹络编程(最重要)、多线程知识(较重要)和其中⼀些⼩技巧。

⼀、I/O流I/O流⽤来处理设备之间的数据传输,Java对数据的传输通过流的⽅式。

流按操作数据分为两种:字节流与字符流。

如果数据是⽂本类型,那么需要使⽤字符流;如果是其他类型,那么使⽤字节流。

简单来说,字符流=字节流+编码表。

流按流向分为:输⼊流(将硬盘中的数据读⼊内存),输出流(将内存中的数据写⼊硬盘)。

简单来说,想要将某⽂件传到⽬的地,需要将此⽂件关联输⼊流,然后将输⼊流中的信息写⼊到输出流中。

将⽬的关联输出流,就可以将信息传输到⽬的地了。

Java提供了⼤量的流对象可供使⽤,其中有两⼤基类,字节流的两个顶层⽗InputStream与OutputStream;字符流的两个顶层⽗类Reader 与Writer。

这些体系的⼦类都以⽗类名作为后缀,⽽⼦类名的前缀就是该对象的功能。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

发送端/ *by小郭*远程文件传输**/import javax.swing.*;import .*;import java.io.*;import java.awt.*;import ng.*;import java.awt.event.*;public class TcpSend extends JFrame implements ActionListener{private JButton button;private JFileChooser chooser;//private FileInputStream in;//private String filename;//byte[] by=new byte[100000];public TcpSend(){super("小郭文件传输发送端");this.setBounds(10,10,400,400);this.setLayout(null);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setResizable(false);this.setVisible(true);chooser=new JFileChooser();button=new JButton("发送");button.setFont(new Font("楷体",Font.PLAIN,30));button.setBounds(0,0,400,400);add(button);button.addActionListener(this);}public void actionPerformed(ActionEvent e){chooser.showOpenDialog(this);if(chooser.showOpenDialog(this)==JFileChooser.CANCEL_OPTION){button.setText("取消文件发送");//小bug 按2次才能取消return;}Send send=new Send(chooser.getSelectedFile());send.start();button.setText("文件已发送");}public static void main(String[] args){new TcpSend();}}//end TcpSendclass Send extends Thread{private File file;private Socket socket;private DataOutputStream Dout;private DataInputStream Din;BufferedInputStream buffered;Send(File file){this.file = file;try{socket= new Socket("localhost",1111);//localhost可以改成IP 如果是内网直接填内网IP 外网的话IP要映射buffered=new BufferedInputStream(socket.getInputStream());//创建一个缓冲区数组,保存套接字s输入流,以便使用Din = new DataInputStream(buffered);//数据输入流,用来读取Dout = new DataOutputStream(socket.getOutputStream());//数据输出流,用来写入由数据输入流读取的数据} catch (IOException e) {e.printStackTrace();}}public void run(){try{Dout.writeUTF(file.getName());//将文件名写入输出流JOptionPane.showMessageDialog(null,"发送的文件是:"+file.getName());boolean isAccepted = Din.readBoolean();//接收端是否读取输入字节if(isAccepted){// JOptionPane.showMessageDialog(null,"对方已经接受文件传输,点击确定开始传输!");BufferedInputStream Bin = new BufferedInputStream(new FileInputStream(file));//创建一个缓冲区数组,保存文件输入流byte[] by = new byte[100000];int l;while(( l =Bin.read(by))!= -1)//从输入流中将各字节读取到by数组中只要不是=-1 如果=-1即到达流末尾就跳出循环{Dout.write(by,0,l);//将by数组中从偏移地址0开始的1个字节写入输出流。

Dout.flush();//清空数据输出流//l = Bin.read(by);多了这一句照成接收的文件大小只有一半的容量}Bin.close();//关闭缓冲输入流// JOptionPane.showMessageDialog(null,file.toString()+"\n文件发送完毕!");}//end if}//end trycatch (IOException e){e.printStackTrace();}finally//保证即使因为异常,try里面的代码不会被执行,但是finally里面的语句还是会执行,这样可以释放一些资源{try{Din.close();//关闭数据输入流Dout.close();//关闭数据输出流socket.close();}catch (IOException e){e.printStackTrace();}}//end finally}//end run()}//end Send(线程类)*2011接收端import javax.swing.*;import .*;import java.io.*;import java.awt.*;import ng.*;import java.awt.event.*;public class TcpReceive extends JFrame implements ActionListener {private JButton button1,button2;private JLabel label;private Socket socket;private ServerSocket ss;private String filename;public TcpReceive(){super("小郭文件传输接收端");this.setBounds(420,420,400,400);setLayout(null);setVisible(true);this.setResizable(false);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);label=new JLabel();label.setText("暂时没收到文件请求,请等待。

");button1=new JButton("Accept");button2=new JButton("Cancel");add(label);add(button1);add(button2);label.setBounds(10,10,300,300);button1.setBounds(60,310,100,30);button2.setBounds(240,310,100,30);button1.addActionListener(this);button2.addActionListener(this);try{ss=new ServerSocket(1111);//绑定到端口1111的服务器套接字while(!ss.isClosed()){socket=ss.accept();//侦听并接受到此套接字的连接DataInputStream Din = new DataInputStream(socket.getInputStream());//数据输入流,用来读取从1111端口接收到的输入流filename = Din.readUTF();//读取对方发过来的字符串(即文件名)label.setText(filename);}}catch (IOException e){if(ss.isClosed())//端口关闭就退出{JOptionPane.showMessageDialog(this,"端口已关闭,程序退出");System.exit(0);}else{ e.printStackTrace();}}}//end构造函数public void actionPerformed(ActionEvent e){if(e.getSource()==button1){JFileChooser chooser=new JFileChooser();chooser.setSelectedFile(new File(filename));//路径抽象化chooser.showSaveDialog(this);chooser.getName(chooser.getSelectedFile());Receive receive = new Receive(chooser.getSelectedFile(),socket);//创建Receive线程对象用来启动线程类if(chooser.showSaveDialog(this)==JFileChooser.APPROVE_OPTION)//bug:按2次保存才保存下来{//System.out.println("bbb");if(chooser.getSelectedFile().exists())//测试此抽象路径名表示的文件或目录是否存在{int over=JOptionPane.showConfirmDialog(this,"文件"+chooser.getSelectedFile().getName()+"已经存在,确定覆盖吗?","覆盖与否",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);if(over==JOptionPane.YES_OPTION)//bug:按2次确定才能执行{//else{System.out.println("aaa");}receive.start();}//end if}//end ifelse{receive.start();} //System.out.println("aaaa");} //bug:按2次取消才能取消第二次取消才打印}//end if}//end ifif(e.getSource()==button2){if(label.getText()=="暂时没收到文件请求,请等待。

相关文档
最新文档