Home> Java> javaTutorial> body text

How to copy local file to network file and upload using Java?

WBOY
Release: 2023-04-25 15:49:08
forward
1380 people have browsed it

    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()); } } } }
    Copy after login
    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); } }
    Copy after login
    Execution result

    Note:The file on the right is the result of copying, The one on the left is not. (mentioned below!)

    How to copy local file to network file and upload using Java?

    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("文件上传成功。"); } } }
    Copy after login

    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); } } } } }
    Copy after login
    Execution effect

    Execution program

    How to copy local file to network file and upload using Java?

    ##Note:

    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

    How to copy local file to network file and upload using Java?

    File after copying

    How to copy local file to network file and upload using Java?

    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 here

    Copy 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 upload

    Note: 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

    Note:

    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 items; try { items = upload.parseRequest(request); Iterator 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(); } } } }
    Copy after login

    In the jsp for uploading files, only one form is needed.

    文件上传

    Copy after login

    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 upload

    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); } }
    Copy after login

    Using the new features of Servlet 3.0, the

    @MultipartConfigannotation 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.)

    Note: In the following code, I am going too far here, but this is exactly what I want to see. of. It is also an input and output stream. Pay attention to comparing this with the examples above.

    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); } }
    Copy after login

    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.

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

    part.write(filename);
    Copy after login

    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!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!