Java实现文件传输
生活随笔
收集整理的這篇文章主要介紹了
Java实现文件传输
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
服務端發送,客戶端接收。服務端持續運行,一旦有客戶端連接就會向客戶端發送文件
import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.ServerSocket; import java.net.Socket;/*** 文件傳輸server(由服務器發送)** @author qxt* @date 2021/3/8 17:38*/ public class SendExaminationPaperServer extends ServerSocket {/*** 服務器端口*/private static final int SERVER_PORT = 8888;/*** 文件路徑*/private String fileURL;private ServerSocket server;public SendExaminationPaperServer(String fileURL) throws Exception {super(SERVER_PORT);this.server = this;this.fileURL = fileURL;System.out.println("ip: "+server.getInetAddress());}/*** 等待連接** @throws Exception*/public void waiting() throws Exception {File file = new File(fileURL);while (true) {//當阻塞時接受新的連入請求Socket client = this.accept();//并建立新的線程進行處理new Handler(client, file);}}/*** 線程處理類** @author Walskor*/private static class Handler implements Runnable {private Socket socket;private FileInputStream fileIn;private DataOutputStream DataOUT;private File file;public Handler(Socket client, File file) {this.socket = client;this.file = file;new Thread(this).start();}@Overridepublic void run() {try {sendFile(file); //傳輸文件if (socket != null) {try {socket.close();} catch (Exception e) {socket = null;System.out.println("Finally error: " + e.getMessage());}}} catch (Exception e) {e.printStackTrace();}}/*** 向客戶端傳輸文件** @throws Exception*/private void sendFile(File file) throws Exception {try {if (file.exists()) {fileIn = new FileInputStream(file);DataOUT = new DataOutputStream(socket.getOutputStream());//文件名和長度DataOUT.writeUTF(file.getName());DataOUT.flush();DataOUT.writeLong(file.length());DataOUT.flush();//開始傳輸文件System.out.println("=========Start to transfer=========");byte[] bytes = new byte[1024];int length = 0;long progress = 0;while ((length = fileIn.read(bytes, 0, bytes.length)) != -1) {DataOUT.write(bytes, 0, length);DataOUT.flush();progress += length;System.out.println("| " + (100 * progress / file.length()) + "% |");}System.out.println();System.out.println("=====File transferred successfully=====");}} catch (Exception e) {e.printStackTrace();} finally { //關閉數據流if (fileIn != null) {fileIn.close();}if (DataOUT != null) {DataOUT.close();}}}}public static void main(String[] args) {System.out.println("Server starting...");try {SendExaminationPaperServer transfer = new SendExaminationPaperServer("文件路徑");transfer.waiting();if (transfer != null) {transfer.close();}} catch (Exception e) {System.out.println("Error: " + e.getMessage());}} } import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.math.RoundingMode; import java.net.Socket; import java.text.DecimalFormat;/*** 文件接收端 Client(由服務器發送)** @author qxt* @date 2021/3/8 17:38*/ public class ReceiveExaminationPaperClient extends Socket {/*** 服務端IP*/private static final String SERVER_IP = "localhost";/*** 服務端端口號*/private static final int SERVER_PORT = 8888;private Socket server;private DataOutputStream outputStream;/*** 保存接收的文件的文件夾路徑*/private final String directoryURL;public ReceiveExaminationPaperClient(String directoryURL) throws Exception {super(SERVER_IP, SERVER_PORT);this.directoryURL = directoryURL;this.server = this;this.outputStream = new DataOutputStream(server.getOutputStream());System.out.println("this cilent[port:" + this.getLocalPort() + "] attach to server successfully");}/*** 發送參數** @throws Exception*/public void send() throws Exception {outputStream.writeUTF("假裝這是一條有用的數據流");//清空數據流outputStream.flush();}/*** 接收文件*/public void receive() {LoadFile loadFile = new LoadFile(this, directoryURL);loadFile.get();System.out.println("end of load");}private static class LoadFile {private Socket socket;public String fileName;public long fileLength;private DataInputStream diStream;private FileOutputStream foStream;private static DecimalFormat dFormat;private final String directoryURL;static {dFormat = new DecimalFormat("#0.0");dFormat.setRoundingMode(RoundingMode.HALF_UP);dFormat.setMinimumFractionDigits(1);dFormat.setMaximumFractionDigits(1);}//設置數字格式,保留一位有效數字public LoadFile(Socket socket, String directoryURL) {this.socket = socket;this.directoryURL = directoryURL;}public void get() {try {diStream = new DataInputStream(socket.getInputStream());//文件名和長度fileName = diStream.readUTF();fileLength = diStream.readLong();File directory = new File(directoryURL);if (!directory.exists()) {directory.mkdir();}File file = new File(directory.getAbsolutePath() + File.separatorChar + fileName);foStream = new FileOutputStream(file);//開始接收文件byte[] bytes = new byte[1024];int length = 0;while ((length = diStream.read(bytes, 0, bytes.length)) != -1) {foStream.write(bytes, 0, length);foStream.flush();}System.out.println("File received [ File Name: " + fileName + " ] [ Size: " + getFormatFileSize(fileLength) + " ] ===");} catch (Exception e) {e.printStackTrace();} finally {try {if (foStream != null) {foStream.close();}if (diStream != null) {diStream.close();}socket.close();} catch (Exception e2) {e2.printStackTrace();}}// end try}// end get/*** 格式化文件大小** @param length* @return*/private String getFormatFileSize(long length) {double size = ((double) length) / (1 << 30);if (size >= 1) {return dFormat.format(size) + "GB";}size = ((double) length) / (1 << 20);if (size >= 1) {return dFormat.format(size) + "MB";}size = ((double) length) / (1 << 10);if (size >= 1) {return dFormat.format(size) + "KB";}return length + "B";}}public static void main(String[] args) {String directoryURL = "保存文件的文件夾路徑";try {ReceiveExaminationPaperClient client = new ReceiveExaminationPaperClient(directoryURL);client.receive();//關閉數據流if (client.outputStream != null) {try {client.outputStream.close();} catch (Exception e) {client.outputStream = null;e.printStackTrace();}}} catch (Exception e) {e.printStackTrace();}} }總結
以上是生活随笔為你收集整理的Java实现文件传输的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一文读懂知识付费SaaS行业:未来发展趋
- 下一篇: db4o数据库文件_繁忙的Java开发人