搜尋
首頁Javajava教程如何使用Java將本機檔案複製到網路檔案並上傳?

    檔案複製

    #檔案複製: 將一個本機檔案從一個目錄,複製到另一個目錄。 (透過本機檔案系統)

    主要程式碼
    package dragon;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    /**
     * 本地文件复制:
     * 将文件从一个地方复制到另一个地方。
     * 
     * @author Alfred
     * */
    public class FileCopy {
    	
    	public FileCopy() {}
    	
    	public void fileCopy(String target, String output) throws IOException {
    		File targetFile = new File(target);
    		File outputPath = new File(output);
    		
    		this.init(targetFile, outputPath);
    		
    		/**注意这里使用了 try with resource 语句,所以不需要显示的关闭流了。
    		 * 而且,再关闭流操作中,会自动调用 flush 方法,如果不放心,
    		 * 可以在每个write 方法后面,强制刷新一下。
    		 * */
    		try (
    			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(targetFile));                //创建输出文件
    			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(outputPath, "copy"+targetFile.getName())))){
    			int hasRead = 0;
    			byte[] b = new byte[1024];
    			while ((hasRead = bis.read(b)) != -1) {
    				bos.write(b, 0, hasRead);
    			}
    		}
    		System.out.println("文件复制成功");
    	}
    	
    	//数据校验及初始化工作
    	private void init(File targetFile, File outputPath) throws FileNotFoundException {
    		if (!targetFile.exists()) {
    			throw new FileNotFoundException("目标文件不存在:"+targetFile.getAbsolutePath());
    		} else {
    			if (!targetFile.isFile()) {
    				throw new FileNotFoundException("目标文件是一个目录:"+targetFile.getAbsolutePath());
    			}
    		}	
    		
    		if (!outputPath.exists()) {
    			if (!outputPath.mkdirs()) {   
    				throw new FileNotFoundException("无法创建输出路径:"+outputPath.getAbsolutePath());
    			}
    		} else {
    			if (!outputPath.isDirectory()) {
    				throw new FileNotFoundException("输出路径不是一个目录:"+outputPath.getAbsolutePath());
    			}
    		}
    	}
    }
    測試類別
    package dragon;
    
    import java.io.IOException;
    
    public class FileCopyTest {
    	public static void main(String[] args) throws IOException {
    		String target = "D:/DB/BuilderPattern.png";
    		String output = "D:/DBC/dragon/";
    		FileCopy copy = new FileCopy();
    		copy.fileCopy(target, output);
    	}
    }
    執行結果

    注意:右邊檔案是複製的結果,左邊的不是。 (下面會提到!)

    如何使用Java將本機檔案複製到網路檔案並上傳?

    說明

    #上面的程式碼只是將一個本地檔案從一個目錄,複製到另一個目錄,還是比較簡單的,這只是一個原理性的程式碼,來說明輸入輸出流的應用。 將檔案從一個地方複製到另一個地方。

    網路檔案傳輸(TCP)

    **網路檔案傳輸(TCP):**使用套接字(TCP)進行演示,檔案從一個地方複製到另一個地方。 (透過網路的方式。)

    主要程式碼

    #Server

    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class Server {
    	public static void main(String[] args) throws IOException {
    		try (
    			ServerSocket server = new ServerSocket(8080)){
    			Socket client = server.accept();			
    			//开始读取文件
    			try (
    				BufferedInputStream bis = new BufferedInputStream(client.getInputStream());
    				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("D:/DBC/dragon", System.currentTimeMillis()+".jpg")))){
    				int hasRead = 0;
    				byte[] b = new byte[1024];
    				while ((hasRead = bis.read(b)) != -1) {
    					bos.write(b, 0, hasRead);
    				}
    			}
    			System.out.println("文件上传成功。");
    		}
    	}
    }

    Client

    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    public class Client {
    	public static void main(String[] args) throws UnknownHostException, IOException {
    		try (Socket client = new Socket("127.0.0.1", 8080)){
    			File file = new File("D:/DB/netFile/001.jpg");	
    			//开始写入文件
    			try (
    				BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    				BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream())){
    				int hasRead = 0;
    				byte[] b = new byte[1024];
    				while ((hasRead = bis.read(b)) != -1) {
    					bos.write(b, 0, hasRead);
    				}
    			}
    		}
    	}
    }
    執行效果

    執行程式

    如何使用Java將本機檔案複製到網路檔案並上傳?

    #注意:這個上傳檔案的目錄和本機檔案複製是在同一個目錄,但是使用的方式不一樣,檔案的命名方式不一樣,使用的是目前的毫秒數。 複製前檔案

    如何使用Java將本機檔案複製到網路檔案並上傳?

    複製後檔案

    如何使用Java將本機檔案複製到網路檔案並上傳?

    #說明

    透過網路的方式使用流,使用傳輸層的TCP協議,綁定了8080 端口,這裡需要一些網路的知識,不過都是最基本的知識。可以看出來,上面這個 Server端和 Client端的程式碼很簡單,甚至沒有實作傳輸檔案的後綴名稱! (哈哈,其實是我對套接字程式設計不太熟悉,傳輸檔名的話,我一開始嘗試,但是沒有成功。不過這個不影響這個例子,套接字我會抽時間來看的。哈!)注意這裡我要表達的意思透過網路將檔案從一個地方複製到另一個地方。 (使用較為的是傳輸層的協定)

    網路檔案傳輸(HTTP)

    HTTP 是建立在TCP/IP 協定之上的應用層協議,傳輸層協定使用起來感覺還是比較麻煩的,不如應用層協定用起來方便。

    網路檔案傳輸(HTTP): 這裡使用 Servlet(3.0以上)(JSP)技術來舉例,就以我們最常使用的檔案上傳為例。

    使用 HTTP 協定將檔案從一個地方複製到另一個地方。

    使用 apache 元件實作檔案上傳

    注意:因為原始的透過 Servlet 上傳檔案較為麻煩,現在都是使用一些元件來達成這個檔案上傳的功能的。 (我還沒找到檔案上傳最原始的寫法,想必應該是很繁瑣的吧!)這裡使用兩個jar包:

    • commons-fileupload-1.4.jar

    • commons-io-2.6.jar

    #注意:在apache 網站可以下載到。

    上傳檔案的 Servlet

    package com.study;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.Iterator;
    import java.util.List;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileItemFactory;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    /**
     * Servlet implementation class UploadServlet
     */
    @WebServlet("/UploadServlet")
    public class UploadServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		//如果不是文件上传的话,直接不处理,这样比较省事
    		if (ServletFileUpload.isMultipartContent(request)) {
    			//获取(或者创建)上传文件的路径
    			String path = request.getServletContext().getRealPath("/image");
    			File uploadPath = new File(path);
    			if (!uploadPath.exists()) {
    				uploadPath.mkdir();
    			}
    			
    			FileItemFactory factory = new DiskFileItemFactory();
    			ServletFileUpload upload = new ServletFileUpload(factory);
    			List<FileItem> items;
    			try {
    				items = upload.parseRequest(request);
    				Iterator<FileItem> it = items.iterator();
    				while (it.hasNext()) {
    					FileItem item = it.next();
    					//处理上传文件
    					if (!item.isFormField()) {
    						String filename = new File(item.getName()).getName();
    						System.out.println(filename);
    						File file = new File(uploadPath, filename);
    						item.write(file);
    						response.sendRedirect("success.jsp");
    					}
    				}
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}
    	}
    }

    #上傳檔案的jsp中,只需要一個form表單即可。

    <h2 id="文件上传">文件上传</h2>
    <form action="NewUpload" method="post"  enctype="multipart/form-data">
        <input type="file" name="image">
        <input type="submit" value="上传">
    </form>

    運行效果

    說明

    #雖然這樣處理對於上傳檔案很好,但是因為使用的都是較成熟的技術,對於想了解輸入輸出流的我們來說,就不是那麼好了。從這個例子中,基本上看不到輸入輸出流的用法了,都被封裝起來了。

    使用 Servlet 3.0 以後的新技術實作檔案上傳

    package com.study;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.UUID;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;
    
    /**
     * Servlet implementation class FileUpload
     */
    @MultipartConfig
    @WebServlet("/FileUpload")
    public class FileUpload extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    	
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		Part part = request.getPart("image");
    		String header = part.getHeader("Content-Disposition");
    		System.out.println(header);
    		String filename = header.substring(header.lastIndexOf("filename=\"")+10, header.lastIndexOf("\""));
    		
    		String fileSuffix = filename.lastIndexOf(".") != -1 ? filename.substring(filename.lastIndexOf(".")) : "";
    		String uploadPath = request.getServletContext().getRealPath("/image");
    		File path = new File(uploadPath);
    		if (!path.exists()) {
    			path.mkdir();
    		}
    		
    		filename = UUID.randomUUID()+fileSuffix;
    		try (
    			BufferedInputStream bis = new BufferedInputStream(part.getInputStream());
    			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(path, filename)))){
    			int hasRead = 0;
    			byte[] b = new byte[1024];
    			while ((hasRead = bis.read(b)) != -1) {
    				bos.write(b, 0, hasRead);
    			}
    		}
    		response.sendRedirect("success.jsp");
    	}
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }

    使用 Servlet 3.0 的新特性實現,這裡使用了 @MultipartConfig註解。 (如果不使用這個註解,會無法正常工作!感興趣的,可以多去了解一下。)

    注意:下面這段程式碼,這裡我捨近求遠了,但是這正是我想要看到的。同樣是輸入輸出流,注意這個和上面的幾個例子做對比。

    try (
    	BufferedInputStream bis = new BufferedInputStream(part.getInputStream());
    		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(path, filename)))){
    		int hasRead = 0;
    		byte[] b = new byte[1024];
    		while ((hasRead = bis.read(b)) != -1) {
    			bos.write(b, 0, hasRead);
    		}
    	}

    不使用apache 元件的更為簡單的方式是下面這種:

    package com.study;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.UUID;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;
    
    /**
     * Servlet implementation class NewUpload
     */
    @MultipartConfig
    @WebServlet("/NewUpload")
    public class NewUpload extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		Part part = request.getPart("image");
    		String header = part.getHeader("Content-Disposition");
    		System.out.println(header);
    		String filename = header.substring(header.lastIndexOf("filename=\"")+10, header.lastIndexOf("\""));
    		String fileSuffix = filename.lastIndexOf(".") != -1 ? filename.substring(filename.lastIndexOf(".")) : "";
    		String uploadPath = request.getServletContext().getRealPath("/image");
    		File path = new File(uploadPath);
    		if (!path.exists()) {
    			path.mkdir();
    		}
    		filename = uploadPath+File.separator+System.currentTimeMillis()+UUID.randomUUID().toString()+fileSuffix;
    		part.write(filename);
    		response.sendRedirect("success.jsp");
    	}
    
    }

    真正寫入檔案的只有這一步了,前面全是處理文件名和上傳檔案路徑相關的程式碼。使用 HTTP 的三種方式都有處理檔案名稱和上傳檔案路徑這段程式碼。

    如果通过这段代码,那就更看不出什么东西来了,只知道这样做,一个文件就会被写入相应的路径。

    part.write(filename);

    以上是如何使用Java將本機檔案複製到網路檔案並上傳?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    陳述
    本文轉載於:亿速云。如有侵權,請聯絡admin@php.cn刪除
    如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?Mar 17, 2025 pm 05:46 PM

    本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

    如何使用適當的版本控制和依賴項管理創建和使用自定義Java庫(JAR文件)?如何使用適當的版本控制和依賴項管理創建和使用自定義Java庫(JAR文件)?Mar 17, 2025 pm 05:45 PM

    本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

    如何使用咖啡因或Guava Cache等庫在Java應用程序中實現多層緩存?如何使用咖啡因或Guava Cache等庫在Java應用程序中實現多層緩存?Mar 17, 2025 pm 05:44 PM

    本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

    如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?Mar 17, 2025 pm 05:43 PM

    本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

    Java的類負載機制如何起作用,包括不同的類載荷及其委託模型?Java的類負載機制如何起作用,包括不同的類載荷及其委託模型?Mar 17, 2025 pm 05:35 PM

    Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA

    See all articles

    熱AI工具

    Undresser.AI Undress

    Undresser.AI Undress

    人工智慧驅動的應用程序,用於創建逼真的裸體照片

    AI Clothes Remover

    AI Clothes Remover

    用於從照片中去除衣服的線上人工智慧工具。

    Undress AI Tool

    Undress AI Tool

    免費脫衣圖片

    Clothoff.io

    Clothoff.io

    AI脫衣器

    AI Hentai Generator

    AI Hentai Generator

    免費產生 AI 無盡。

    熱門文章

    R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
    3 週前By尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O.最佳圖形設置
    3 週前By尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O.如果您聽不到任何人,如何修復音頻
    3 週前By尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25:如何解鎖Myrise中的所有內容
    4 週前By尊渡假赌尊渡假赌尊渡假赌

    熱工具

    SublimeText3 Mac版

    SublimeText3 Mac版

    神級程式碼編輯軟體(SublimeText3)

    記事本++7.3.1

    記事本++7.3.1

    好用且免費的程式碼編輯器

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

    EditPlus 中文破解版

    EditPlus 中文破解版

    體積小,語法高亮,不支援程式碼提示功能

    SublimeText3 Linux新版

    SublimeText3 Linux新版

    SublimeText3 Linux最新版