教育路上
摘要:java 實現 文件 上傳 服務器端 和 客戶端 ,實現文件上傳服務器端和客戶端,掌握文件上傳的實現思路。以下是我們為大家整理的,相信大家閱讀完后肯定有了自己的選擇吧。
2022-05-12 21:26網絡推薦
文件上傳
任務介紹:實現文件上傳服務器端和客戶端
任務目標:掌握文件上傳的實現思路
實現思路:文件上傳客戶端中將打開一個指定文件并從該文件中讀取字節流到緩沖區 buffer
中,然后將緩沖區中的數據寫入到網絡流中。在文件上傳服務器中,先從網絡流中讀取數據
到緩沖區,再將緩沖區數據寫入到文件流中。
實現代碼
import java.io.*;
import java.net.*;
public class FileClient {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1", 10001); // 創建客戶端 Socket
OutputStream out = socket.getOutputStream(); // 獲取 Socket 的輸出流對象
// 創建 FileInputStream 對象
FileInputStream fis = new FileInputStream("F:\\1.jpg");
byte[] buf = new byte[1024]; // 定義一個字節數組
int len; // 定義一個 int 類型的變量 len
while ((len = fis.read(buf)) != -1) { // 循環讀取數據
out.write(buf, 0, len);
}
socket.shutdownOutput(); // 關閉客戶端輸出流
InputStream in = socket.getInputStream(); // 獲取 Socket 的輸入流對象
byte[] bufMsg = new byte[1024]; // 定義一個字節數組
int num = in.read(bufMsg); // 接收服務端的信息
String Msg = new String(bufMsg, 0, num);
System.out.println(Msg);
fis.close(); // 關鍵輸入流對象
socket.close(); // 關閉 Socket 對象
}
}
import java.io.*;
import java.net.*;
public class FileServer {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(10001); // 創建 ServerSocket 對象
while (true) {
// 調用 accept()方法接收客戶端請求,得到 Socket 對象
Socket s = serverSocket.accept();
// 每當和客戶端建立 Socket 連接后,單獨開啟一個線程處理和客戶端的交互
new Thread(new ServerThread(s)).start();
}
}
}
class ServerThread implements Runnable {
private Socket socket; // 持有一個 Socket 類型的屬性
public ServerThread(Socket socket) { // 構造方法中把 Socket 對象作為實參傳入
this.socket = socket;
}
public void run() {
String ip = socket.getInetAddress().getHostAddress(); // 獲取客戶端的 IP 地址
int count = 1; // 上傳圖片個數
try {
InputStream in = socket.getInputStream();
File parentFile = new File("F:\\upload\\"); // 創建上傳圖片目錄的 File 對象
if (!parentFile.exists()) { // 如果不存在,就創建這個目錄
parentFile.mkdir();
}
// 把客戶端的 IP 地址作為上傳文件的文件名
File file = new File(parentFile, ip + "(" + count + ").jpg");
while (file.exists()) {
// 如果文件名存在,則把 count++
file = new File(parentFile, ip + "(" + (count++) + ").jpg");
}
// 創建 FileOutputStream 對象
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024]; // 定義一個字節數組
int len = 0; // 定義一個 int 類型的變量 len,初始值為 0
while ((len = in.read(buf)) != -1) { // 循環讀取數據
fos.write(buf, 0, len);
}
OutputStream out = socket.getOutputStream();// 獲取服務端的輸出流
out.write("上傳成功".getBytes()); // 上傳成功后向客戶端寫出“上傳成功”
fos.close(); // 關閉輸出流對象
socket.close(); // 關閉 Socket 對象
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
訪客的評論 2023/11/08 20:46
文中描述的是準確的嗎,如何報名!