How to copy local file to network file and upload using Java?
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>
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);
}
}
Copy after login
Using the new features of Servlet 3.0, the 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); } }
@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");
}
}
Copy after login
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. 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"); } }
如果通过这段代码,那就更看不出什么东西来了,只知道这样做,一个文件就会被写入相应的路径。
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.
