DataClient(服務器端上傳文件到客戶端)

本文介绍了一个使用Java实现的简单网络文件传输客户端程序。该客户端能够连接到指定服务器地址及端口,接收从服务器发送来的文件,并将其保存到本地路径。程序通过Socket建立连接,并利用输入输出流进行数据读写。
import java.io.*;
import java.net.*;

import java.net.*;
import java.io.*;


public class DataClient {

        public static final int SERVICE_PORT = 1500;
        public static final int DATA_SIZE = 1024;

        public static void main(String[] args) {
                String hostName="10.100.100.100";
                
                String filePath="C:"+File.separatorChar+"電話號碼_Tel.xls";
                        try{
                        Socket client = new Socket(hostName,SERVICE_PORT);
                        System.out.println("Connection established");
                        System.out.println(client.getRemoteSocketAddress());
                        client.setSoTimeout(2000);
                        File file=new File(filePath);
                        if(file.exists()){
                            file.delete();
                            System.out.println("Create new file");
                        }
                        InputStream in = client.getInputStream();
                        BufferedReader readerFile = new BufferedReader(
                                        new InputStreamReader(in));
                        

                        DataInputStream reader = new DataInputStream(in);
                        
                        FileOutputStream fos = new FileOutputStream(file);
                        String filename=readerFile.readLine();
                        System.out.println("FileName:---------->>>>>>" + filename);
                        
                        byte[] bs = new byte[DATA_SIZE];
		                int length;
		                System.out.println("Data receiving started");
		                while( (length=reader.read(bs)) != -1){
		                        fos.write(bs,0,length);
		                        bs = new byte[DATA_SIZE];
		                        Thread.sleep(200);
		                }
		                System.out.println("Receiving completed");
		                readerFile.close();
		                reader.close();
		                fos.close();        
                }catch(Exception e){
                        e.printStackTrace();
                }

        }

} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值