File copy
File copy:Copy a local file from one directory to another Table of contents. (Through local file system)
Main code
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()); } } } }
Test class
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); } }
Execution result
Note: The file on the right is the result of copying, The one on the left is not. (mentioned below!)
Explanation
The above code just copies a local file from one directory to another. It is still relatively simple. This is just a principle code to illustrate the application of input and output streams. Copy files from one place to another.
Network File Transfer (TCP)
**Network File Transfer (TCP): **Using sockets (TCP) for demonstration, files are copied from one place to another place. (Through the network.)
Main code
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); } } } } }
Execution effect
Execution program
Copy the directory and local file of this uploaded file It is in the same directory, but the method used is different, the file is named differently, and the current milliseconds are used. File before copying
File after copying
Instructions
Use streams through the network, use the TCP protocol of the transport layer, and bind port 8080. Some network knowledge is required here, but it is the most basic knowledge. It can be seen that the above server-side and client-side codes are very simple, and they do not even implement the suffix name of the transferred file! (Haha, actually I am not very familiar with socket programming. When it comes to transferring file names, I tried it at first, but failed. However, this does not affect this example. I will take the time to look at sockets. Ha!) Note what I mean hereCopy files from one place to another over the network. (The more used is the transport layer protocol)
Network file transfer (HTTP)HTTP is an application layer protocol built on the TCP/IP protocol, and the transport layer protocol uses It seems to be quite cumbersome and not as convenient to use as the application layer protocol.Network file transfer (HTTP): Here we use Servlet (3.0 or above) (JSP) technology as an example, taking our most commonly used file upload as an example.
Copy files from one place to another using HTTP protocol.
Use apache components to implement file uploadNote: Because the original file upload through Servlet is more troublesome, some components are now used to achieve this file upload function. (I haven’t found the most original way to write file upload. It must be very cumbersome!) Two jar packages are used here:commons-fileupload-1.4.jar
commons-io-2.6.jar
can be downloaded from the apache website .
Servlet for uploading files
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(); } } } }
In the jsp for uploading files, only one form is needed.
<h2 id="文件上传">文件上传</h2> <form action="NewUpload" method="post" enctype="multipart/form-data"> <input type="file" name="image"> <input type="submit" value="上传"> </form>Operation effect
Explanation
Although this processing is good for uploading files, it uses relatively mature technologies. , for those of us who want to understand the input and output streams, it is not so good. From this example, you can basically not see the usage of input and output streams, they are all encapsulated. Using new technologies after Servlet 3.0 to implement file uploadpackage 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);
}
}
Using the new features of Servlet 3.0, the @MultipartConfig annotation is used here. (If you don’t use this annotation, it will not work properly! If you are interested, you can learn more about it.)
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); } }
The simpler way without using the apache component is the following: 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");
}
}
The only step that actually writes the file is to process the file. Code related to the name and uploaded file path. These three methods of using HTTP all have code that handles file names and uploaded file paths.
如果通过这段代码,那就更看不出什么东西来了,只知道这样做,一个文件就会被写入相应的路径。
part.write(filename);
The above is the detailed content of How to copy local file to network file and upload using Java?. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor