JAVA 传输文件

//以前写的一个文件传输的小程序,有客户端和服务器端两部分,服务器可//以一直运行,客户端传输完一个后退出,当然你也可以根据你的需要改。

//服务器端可以支持多个客户端同时上传,用到了多线程

* 文件传输,客户端

* @aurth anyx

//package per.anyx.ftp;

import java.net.*;

import java.io.*;

public class FtpClient{

public static void main(String[] args){

if(args.length != 3){

System.out.println(“Usage: FtpClient host_add host_port src_file”);

System.exit(0);

File file = new File(args[2]);

if(!file.exists() || !file.isFile()){

System.out.println(“File \”” + args[2] + “\” does not exist or is not a normal file.”);

System.exit(0);

Socket s = null;

FileInputStream in = null;

OutputStream out = null;

try{

s = new Socket(args[0], Integer.parseInt(args[1]));

in = new FileInputStream(file);

out = s.getOutputStream();

byte[] buffer = new byte[1024*8];

int len = -1;

System.out.println(“File tansfer statr…”);

while((len=in.read(buffer)) != -1){

out.write(buffer, 0, len);

System.out.println(“File tansfer complete…”);

}catch(Exception e){

System.out.println(“Error: ” + e.getMessage());

System.exit(1);

}finally{

try{

if(in != null) in.close();

if(out != null) out.close();

if(s != null) s.close();

}catch(Exception e){}

* 文件传输,服务器端

* @aurth anyx

//package per.anyx.ftp;

import java.net.*;

import java.io.*;

public class FtpServer{

public static void main(String[] args){

if(args.length != 1){

System.out.println(“Usage: FtpServer server_port”);

System.exit(0);

ServerSocket ss = null;

try{

ss = new ServerSocket(Integer.parseInt(args[0]));

System.out.println(“FtpServer start on port …” + args[0]);

while(true){

Socket s = ss.accept();

new FtpThread(s).start();

System.out.println(s.getInetAddress().getHostAddress() + ” connected.”);

}catch(Exception e){

System.out.println(“Error: ” + e.getMessage());

}finally{

try{

if(ss != null) ss.close();

}catch(Exception e){}

class FtpThread extends Thread{

Socket s;

long fileName = 0;

public FtpThread(Socket s){

this.s = s;

public void run(){

FileOutputStream out = null;

InputStream in = null;

File file = null;

file = new File(“” + (fileName++));

}while(file.exists());

try{

out = new FileOutputStream(file);

in = s.getInputStream();

byte[] buffer = new byte[1024*8];

int len = -1;

while((len=in.read(buffer)) != -1){

out.write(buffer, 0, len);

}catch(Exception e){

System.out.println(“Error: ” + e.getMessage());

}finally{

try{

if(in != null) in.close();

if(out != null) out.close();

if(s != null) s.close();

System.out.println(s.getInetAddress().getHostAddress() + ” connect closed..”);

}catch(Exception e){}

java文件传输

利用java socket实现文件传输

1.服务器端

package sterning;

import java.io.BufferedInputStream;

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.net.ServerSocket;

import java.net.Socket;

public class ServerTest {

int port = 8821;

void start() {

Socket s = null;

try {

ServerSocket ss = new ServerSocket(port);

while (true) {

// 选择进行传输的文件

String filePath = “D:\\lib.rar”;

File fi = new File(filePath);

System.out.println(“文件长度:” + (int) fi.length());

// public Socket accept() throws

// IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。

s = ss.accept();

System.out.println(“建立socket链接”);

DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));

dis.readByte();

DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));

DataOutputStream ps = new DataOutputStream(s.getOutputStream());

//将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,具体可以参见Think In Java 4th里有现成的代码。

ps.writeUTF(fi.getName());

ps.flush();

ps.writeLong((long) fi.length());

ps.flush();

int bufferSize = 8192;

byte[] buf = new byte[bufferSize];

while (true) {

int read = 0;

if (fis != null) {

read = fis.read(buf);

}

if (read == -1) {

break;

}

ps.write(buf, 0, read);

}

ps.flush();

// 注意关闭socket链接哦,不然客户端会等待server的数据过来,

// 直到socket超时,导致数据不完整。

fis.close();

s.close();

System.out.println(“文件传输完成”);

}

} catch (Exception e) {

e.printStackTrace();

}

}

public static void main(String arg[]) {

new ServerTest().start();

}

2.socket的Util辅助类

package sterning;

import java.net.*;

import java.io.*;

public class ClientSocket {

private String ip;

private int port;

private Socket socket = null;

DataOutputStream out = null;

DataInputStream getMessageStream = null;

public ClientSocket(String ip, int port) {

this.ip = ip;

this.port = port;

}

/** *//**

* 创建socket连接

*

* @throws Exception

*exception

*/

public void CreateConnection() throws Exception {

try {

socket = new Socket(ip, port);

} catch (Exception e) {

e.printStackTrace();

if (socket != null)

socket.close();

throw e;

} finally {

}

}

public void sendMessage(String sendMessage) throws Exception {

try {

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

if (sendMessage.equals(“Windows”)) {

out.writeByte(0x1);

out.flush();

return;

}

if (sendMessage.equals(“Unix”)) {

out.writeByte(0x2);

out.flush();

return;

}

if (sendMessage.equals(“Linux”)) {

out.writeByte(0x3);

out.flush();

} else {

out.writeUTF(sendMessage);

out.flush();

}

} catch (Exception e) {

e.printStackTrace();

if (out != null)

out.close();

throw e;

} finally {

}

}

public DataInputStream getMessageStream() throws Exception {

try {

getMessageStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

return getMessageStream;

} catch (Exception e) {

e.printStackTrace();

if (getMessageStream != null)

getMessageStream.close();

throw e;

} finally {

}

}

public void shutDownConnection() {

try {

if (out != null)

out.close();

if (getMessageStream != null)

getMessageStream.close();

if (socket != null)

socket.close();

} catch (Exception e) {

}

}

3.客户端

package sterning;

import java.io.BufferedOutputStream;

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.FileOutputStream;

public class ClientTest {

private ClientSocket cs = null;

private String ip = “localhost”;// 设置成服务器IP

private int port = 8821;

private String sendMessage = “Windwos”;

public ClientTest() {

try {

if (createConnection()) {

sendMessage();

getMessage();

}

} catch (Exception ex) {

ex.printStackTrace();

}

}

private boolean createConnection() {

cs = new ClientSocket(ip, port);

try {

cs.CreateConnection();

System.out.print(“连接服务器成功!” + “\n”);

return true;

} catch (Exception e) {

System.out.print(“连接服务器失败!” + “\n”);

return false;

}

}

private void sendMessage() {

if (cs == null)

return;

try {

cs.sendMessage(sendMessage);

} catch (Exception e) {

System.out.print(“发送消息失败!” + “\n”);

}

}

private void getMessage() {

if (cs == null)

return;

DataInputStream inputStream = null;

try {

inputStream = cs.getMessageStream();

} catch (Exception e) {

System.out.print(“接收消息缓存错误\n”);

return;

}

try {

//本地保存路径,文件名会自动从服务器端继承而来。

String savePath = “E:\\”;

int bufferSize = 8192;

byte[] buf = new byte[bufferSize];

int passedlen = 0;

long len=0;

savePath += inputStream.readUTF();

DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savePath))));

len = inputStream.readLong();

System.out.println(“文件的长度为:” + len + “\n”);

System.out.println(“开始接收文件!” + “\n”);

while (true) {

int read = 0;

if (inputStream != null) {

read = inputStream.read(buf);

}

passedlen += read;

if (read == -1) {

break;

}

//下面进度条本为图形界面的prograssBar做的,这里如果是打文件,可能会重复打印出一些相同的百分比

System.out.println(“文件接收了” + (passedlen * 100/ len) + “%\n”);

fileOut.write(buf, 0, read);

}

System.out.println(“接收完成,文件存为” + savePath + “\n”);

fileOut.close();

} catch (Exception e) {

System.out.println(“接收消息错误” + “\n”);

return;

}

}

public static void main(String arg[]) {

new ClientTest();

}

}代码如下:

importjava.io.*;

importjava.net.*;

importjava.util.*;

privateHttpURLConnectionconnection;//存储连接

privateintdownsize=-1;//下载文件大小,初始值为-1

privateintdowned=0;//文加已下载大小,初始值为0

privateRandomAccessFilesavefile;//记录下载信息存储文件

privateURLfileurl;//记录要下载文件的地址

privateDataInputStreamfileStream;//记录下载的数据流

try{

/*开始创建下载的存储文件,并初始化值*/

Filetempfileobject=newFile(“h:\\webwork-2.1.7.zip”);

if(!tempfileobject.exists()){

/*文件不存在则建立*/

tempfileobject.createNewFile();

}

savefile=newRandomAccessFile(tempfileobject,”rw”);

/*建立连接*/

fileurl=newURL(“”);

connection=(HttpURLConnection)fileurl.openConnection();

connection.setRequestProperty(“Range”,”byte=”+this.downed+”-“);

this.downsize=connection.getContentLength();

//System.out.println(connection.getContentLength());

newThread(this).start();

catch(Exceptione){

System.out.println(e.toString());

System.out.println(“构建器错误”);

System.exit(0);

publicvoidrun(){

/*开始下载文件,以下测试非断点续传,下载的文件存在问题*/

try{

System.out.println(“begin!”);

Datebegintime=newDate();

begintime.setTime(newDate().getTime());

byte[]filebyte;

intonecelen;

//System.out.println(this.connection.getInputStream().getClass().getName());

this.fileStream=newDataInputStream(

newBufferedInputStream(

this.connection.getInputStream()));

System.out.println(“size=”+this.downsize);

while(this.downsize!=this.downed){

if(this.downsize-this.downed>262144){//设置为最大256KB的缓存

filebyte=newbyte[262144];

onecelen=262144;

}

else{

filebyte=newbyte[this.downsize-this.downed];

onecelen=this.downsize-this.downed;

}

onecelen=this.fileStream.read(filebyte,0,onecelen);

this.savefile.write(filebyte,0,onecelen);

this.downed+=onecelen;

System.out.println(this.downed);

}

this.savefile.close();

System.out.println(“end!”);

System.out.println(begintime.getTime());

System.out.println(newDate().getTime());

System.out.println(begintime.getTime()-newDate().getTime());

}

catch(Exception e){

System.out.println(e.toString());

System.out.println(“run()方法有问题!”);

//FileClient.java

import java.io.*;

import java.net.*;

public class FileClient {

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

//使用本地文件系统接受网络数据并存为新文件

File file = new File(“d:\\fmd.doc”);

file.createNewFile();

RandomAccessFile raf = new RandomAccessFile(file, “rw”);

// 通过Socket连接文件服务器

Socket server = new Socket(InetAddress.getLocalHost(), 3318);

//创建网络接受流接受服务器文件数据

InputStream netIn = server.getInputStream();

InputStream in = new DataInputStream(new BufferedInputStream(netIn));

//创建缓冲区缓冲网络数据

byte[] buf = new byte[2048];

int num = in.read(buf);

while (num != (-1)) {//是否读完所有数据

raf.write(buf, 0, num);//将数据写往文件

raf.skipBytes(num);//顺序写文件字节

num = in.read(buf);//继续从网络中读取文件

in.close();

raf.close();

//FileServer.java

import java.io.*;

import java.util.*;

import java.net.*;

public class FileServer {

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

//创建文件流用来读取文件中的数据

File file = new File(“d:\\系统特点.doc”);

FileInputStream fos = new FileInputStream(file);

//创建网络服务器接受客户请求

ServerSocket ss = new ServerSocket(8801);

Socket client = ss.accept();

//创建网络输出流并提供数据包装器

OutputStream netOut = client.getOutputStream();

OutputStream doc = new DataOutputStream(

new BufferedOutputStream(netOut));

//创建文件读取缓冲区

byte[] buf = new byte[2048];

int num = fos.read(buf);

while (num != (-1)) {//是否读完文件

doc.write(buf, 0, num);//把文件数据写出网络缓冲区

doc.flush();//刷新缓冲区把数据写往客户端

num = fos.read(buf);//继续从文件中读取数据

fos.close();

doc.close();

*/java中的网络信息传输方式基于TCP协议和UD协议P的,socket是基于TCP协议的实现代码如下:

import java.io.DataOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.net.InetSocketAddress;

import java.net.Socket;

public class ClientTcpSend {

public static void main(String[] args) {

int length = 0;

byte[] sendBytes = null;

Socket socket = null;

DataOutputStream dos = null;

FileInputStream fis = null;

try {

try {

socket = new Socket();

socket.connect(new InetSocketAddress(“127.0.0.1”, 33456),

dos = new DataOutputStream(socket.getOutputStream());

File file = new File(“/root/6674541037_c3a9c8b64c_b.jpg”);

Ffis = new FileInputStream(file);

sendBytes = new byte[1024];

while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {

dos.write(sendBytes, 0, length);

dos.flush();

} finally {

if (dos != null)

dos.close();

if (fis != null)

fis.close();

if (socket != null)

socket.close();

} catch (Exception e) {

e.printStackTrace();

}

}