附件存储以及复制概述

94 阅读1分钟

我们在做管理类软件时基本上都有附件上传、复制等要求。常规操作是每上传和复制时都存储一次文件到我们的服务器上。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopy {
    public static void main(String[] args) {
        String sourceFile = "path/to/source/file.ext"; // 源文件路径
        String destinationFile = "path/to/destination/file.ext"; // 目标文件路径
        try {
            // 创建输入流和输出流
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);
            // 创建缓冲区
            byte[] buffer = new byte[1024];
            int bytesRead;
            // 循环从输入流读取数据,并写入输出流中
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }
            // 关闭流
            fileInputStream.close();
            fileOutputStream.close();
            System.out.println("文件复制成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

但是当我们频繁复制和上传大文件,比如视频类文件时;可能会导致服务器内存不够用。所以在文件复制时,我们可以采用另一种方式。即:若待上传的附件信息已在服务器上,则不执行物理文件的复制,直接创建一个相同的索引,显示在需要的地方即可。 如果是删除操作,则我们不能直接把物理文件删除,因为要判断是否有其他界面指向此附件。 采取这种方式能一定程度的避免文件服务器内存不够问题。