javaio传输文件
1. 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;
do{
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){}
}
}
}
2. java socket传送文件
客户端代码如下:
importjava.io.DataOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.net.InetSocketAddress;
importjava.net.Socket;
/**
*文件发送客户端主程序
*@authoradmin_Hzw
*
*/
publicclassBxClient{
/**
*程序main方法
*@paramargs
*@throwsIOException
*/
publicstaticvoidmain(String[]args)throwsIOException{
intlength=0;
doublesumL=0;
byte[]sendBytes=null;
Socketsocket=null;
DataOutputStreamdos=null;
FileInputStreamfis=null;
booleanbool=false;
try{
Filefile=newFile("D:/天啊.zip");//要传输的文件路径
longl=file.length();
socket=newSocket();
socket.connect(newInetSocketAddress("127.0.0.1",48123));
dos=newDataOutputStream(socket.getOutputStream());
fis=newFileInputStream(file);
sendBytes=newbyte[1024];
while((length=fis.read(sendBytes,0,sendBytes.length))>0){
sumL+=length;
System.out.println("已传输:"+((sumL/l)*100)+"%");
dos.write(sendBytes,0,length);
dos.flush();
}
//虽然数据类型不同,但JAVA会自动转换成相同数据类型后在做比较
if(sumL==l){
bool=true;
}
}catch(Exceptione){
System.out.println("客户端文件传输异常");
bool=false;
e.printStackTrace();
}finally{
if(dos!=null)
dos.close();
if(fis!=null)
fis.close();
if(socket!=null)
socket.close();
}
System.out.println(bool?"成功":"失败");
}
}
服务端代码如下:
importjava.io.DataInputStream;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.net.ServerSocket;
importjava.net.Socket;
importjava.util.Random;
importcom.boxun.util.GetDate;
/**
*接收文件服务
*@authoradmin_Hzw
*
*/
publicclassBxServerSocket{
/**
*工程main方法
*@paramargs
*/
publicstaticvoidmain(String[]args){
try{
finalServerSocketserver=newServerSocket(48123);
Threadth=newThread(newRunnable(){
publicvoidrun(){
while(true){
try{
System.out.println("开始监听...");
/*
*如果没有访问它会自动等待
*/
Socketsocket=server.accept();
System.out.println("有链接");
receiveFile(socket);
}catch(Exceptione){
System.out.println("服务器异常");
e.printStackTrace();
}
}
}
});
th.run();//启动线程运行
}catch(Exceptione){
e.printStackTrace();
}
}
publicvoidrun(){
}
/**
*接收文件方法
*@paramsocket
*@throwsIOException
*/
publicstaticvoidreceiveFile(Socketsocket)throwsIOException{
byte[]inputByte=null;
intlength=0;
DataInputStreamdis=null;
FileOutputStreamfos=null;
StringfilePath="D:/temp/"+GetDate.getDate()+"SJ"+newRandom().nextInt(10000)+".zip";
try{
try{
dis=newDataInputStream(socket.getInputStream());
Filef=newFile("D:/temp");
if(!f.exists()){
f.mkdir();
}
/*
*文件存储位置
*/
fos=newFileOutputStream(newFile(filePath));
inputByte=newbyte[1024];
System.out.println("开始接收数据...");
while((length=dis.read(inputByte,0,inputByte.length))>0){
fos.write(inputByte,0,length);
fos.flush();
}
System.out.println("完成接收:"+filePath);
}finally{
if(fos!=null)
fos.close();
if(dis!=null)
dis.close();
if(socket!=null)
socket.close();
}
}catch(Exceptione){
e.printStackTrace();
}
}
}
3. java如何实现 io流传输过来的文件,提示另存为弹出窗口
弹出窗口,我理解为浏览器弹出窗口,所以必定有后端服务器程序,这里重点说的就是服务器程序。
第一步:设置Response头部(最关键)
response.setContentType("application/octet-stream;charset=UTF-8");
// 设置弹出框提示的文件名
response.addHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
第二步:解析输入流
// 这里的in为你的输入流
BufferedInputStream is = new BufferedInputStream(in);
// 准备缓冲区
byte[] buffer = new byte[4096];
第三步:将输入流转换为输出流
BufferedOutputStream os = new BufferedOutputStream(response.getOutputStream());
int offset = 0;
while((offset = is.read(buffer, 0, 4096) > -1) {
os.write(buffer, 0, offset)
}
第四步:关闭输入输出流
os.close();
is.close();