Java之Socket实现文件传输
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                Java之Socket实现文件传输
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                流操作
DataInputStream:數據輸入流 讀取基本 Java 數據類型
 DataOutputStream:數據輸出流 寫出基本 Java 數據類型
Socket客戶端
import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.Socket;public class SocketClientTest extends Socket {private final String SERVER_IP="127.0.0.1";private final int SERVER_PORT=9019;private Socket client;private FileInputStream fis;private DataOutputStream dos;//創建客戶端,并指定接收的服務端IP和端口號public SocketClientTest() throws IOException {this.client=new Socket(SERVER_IP,SERVER_PORT);System.out.println("成功連接服務端..."+SERVER_IP);}//向服務端傳輸文件public void sendFile(String url) throws IOException {File file=new File(url);try {fis = new FileInputStream(file);//BufferedInputStream bi=new BufferedInputStream(new InputStreamReader(new FileInputStream(file),"GBK"));dos = new DataOutputStream(client.getOutputStream());//client.getOutputStream()返回此套接字的輸出流//文件名、大小等屬性dos.writeUTF(file.getName());dos.flush();dos.writeLong(file.length());dos.flush();// 開始傳輸文件System.out.println("======== 開始傳輸文件 ========");byte[] bytes = new byte[1024];int length = 0;while ((length = fis.read(bytes, 0, bytes.length)) != -1) {dos.write(bytes, 0, length);dos.flush();}System.out.println("======== 文件傳輸成功 ========");}catch(IOException e){e.printStackTrace();System.out.println("客戶端文件傳輸異常");}finally{fis.close();dos.close();}}public static void main(String[] args) {try {SocketClientTest client = new SocketClientTest(); // 啟動客戶端連接client.sendFile("D:\\file\\work\\test\\a.pdf"); // 傳輸文件} catch (Exception e) {e.printStackTrace();}} }Socket服務端
import java.io.DataInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket;public class SocketServerTest {private static final int SERVER_PORT = 9019; // 服務端端口private ServerSocket server;private Socket socket;private DataInputStream dis;private FileOutputStream fos;public SocketServerTest() throws Exception {server=new ServerSocket(SERVER_PORT);}public void task() throws IOException {System.out.println("======== 等待連接 ========");Socket socket = server.accept();System.out.println(" Ip:"+socket.getInetAddress()+"已連接");try {dis = new DataInputStream(socket.getInputStream());// 文件名和長度String fileName = dis.readUTF();long fileLength = dis.readLong();File directory = new File("D:\\file\\work");if(!directory.exists()) {directory.mkdir();}File file = new File(directory.getAbsolutePath() + File.separatorChar + fileName);fos = new FileOutputStream(file);System.out.println("file。。。。。。。。。。。。。。"+file);System.out.println("fileName。。。。。。。。。。。。。。"+fileName);System.out.println("======== 開始接收文件 ========");byte[] bytes = new byte[1024];int length = 0;while((length = dis.read(bytes, 0, bytes.length)) != -1) {fos.write(bytes, 0, length);fos.flush();}System.out.println("======== 文件接收成功 ========");} catch (Exception e) {e.printStackTrace();} finally {try {if(fos != null)fos.close();if(dis != null)dis.close();socket.close();} catch (IOException e) {e.printStackTrace();}}}public static void main(String[] args) {try {SocketServerTest server = new SocketServerTest(); // 啟動服務端server.task();} catch (Exception e) {e.printStackTrace();}} }Socket服務端之線程優化
import java.io.DataInputStream; import java.io.File; import java.io.FileOutputStream; import java.net.ServerSocket; import java.net.Socket;public class Server extends ServerSocket {private static final int SERVER_PORT = 9019; // 服務端端口private ServerSocket server;public Server() throws Exception {server=new ServerSocket(SERVER_PORT);}/*** 使用線程處理每個客戶端傳輸的文件* @throws Exception*/public void load() throws Exception {while (true) {System.out.println("-----------等待連接-------- ");Socket socket = server.accept();//接收連接服務端的客戶端對象System.out.println("ip" + socket.getInetAddress() + "已連接");new Thread(new Transfer(socket),"thread1").start();// 每接收到一個Socket就建立一個新的線程來處理它System.out.println(Thread.currentThread().getName());}}/*** 處理客戶端傳輸過來的文件線程類*/class Transfer implements Runnable {private Socket socket;private DataInputStream dis;private FileOutputStream fos;public Transfer(Socket socket) {this.socket = socket;}@Overridepublic void run() {try {dis = new DataInputStream(socket.getInputStream());// 文件名和長度String fileName = dis.readUTF();long fileLength = dis.readLong();File directory = new File("E:/xn");if(!directory.exists()) {directory.mkdir();}File file = new File(directory.getAbsolutePath() + File.separatorChar + fileName);System.out.println("file"+file);fos = new FileOutputStream(file);// 開始接收文件byte[] bytes = new byte[1024];int length = 0;while((length = dis.read(bytes, 0, bytes.length)) != -1) {fos.write(bytes, 0, length);fos.flush();}System.out.println("======== 文件接收成功 [File Name:" + fileName + "] ");} catch (Exception e) {e.printStackTrace();} finally {try {if(fos != null)fos.close();if(dis != null)dis.close();} catch (Exception e) {e.printStackTrace();}}}}public static void main(String[] args) {try {Server server = new Server(); // 啟動服務端server.load();} catch (Exception e) {e.printStackTrace();}} }總結
以上是生活随笔為你收集整理的Java之Socket实现文件传输的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 京东api接入的几个坑(宙斯) 转载
 - 下一篇: wow服务器文件夹,《60级魔兽世界WT