有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在下载时创建只读文件

我的要求是使用SpringMVC以只读格式上传一个文件,并以只读格式下载相同的文件。 我能够上传只读格式的文件,但下载后它失去了只读属性

文件上传代码:-

File destinationFile = new File ( targetPath);

try {
    FileOutputStream out = new FileOutputStream( destinationFile );

    byte[] bytes = file.getBytes();
    stream = new BufferedOutputStream(out);
    stream.write(bytes);

    destinationFile.setReadOnly();
    destinationFile.setWritable(false);

}finally {
    if(stream != null){
        stream.close();
    }
} 

下载代码:-

File file = new File(folderPath);
contentType = "application/octet-stream";

response.setBufferSize(BUFFER_SIZE);
response.setHeader("Content-Disposition", disposition + ";filename=\"" + filename  + "\"");

RandomAccessFile input = new RandomAccessFile(file, "r");
OutputStream output = response.getOutputStream();
long start, long length;

byte[] buffer = new byte[BUFFER_SIZE];
int read;

if (input.length() == length) {
    while ((read = input.read(buffer)) > 0) {
        output.write(buffer, 0, read);
    }
} else {
    input.seek(start);
    long toRead = length;

    while ((read = input.read(buffer)) > 0) {
        if ((toRead -= read) > 0) {
            output.write(buffer, 0, read);
        } else {
            output.write(buffer, 0, (int) toRead + read);
            break;
        }
    }
}

有什么建议吗


共 (2) 个答案

  1. # 1 楼答案

    您必须使用以下设置自己的只读属性:

    file.setReadOnly();
    

    documentation of the setReadOnly method开始:

    public boolean setReadOnly()

    Marks the file or directory named by this abstract pathname so that only read operations are allowed. After invoking this method the file or directory will not change until it is either deleted or marked to allow write access. On some platforms it may be possible to start the Java virtual machine with special privileges that allow it to modify files that are marked read-only. Whether or not a read-only file or directory may be deleted depends upon the underlying system.

  2. # 2 楼答案

    不幸的是,这是不可能的

    一旦文件位于您无法控制的用户机器上,您就无法强制执行有关该文件的任何内容

    您可以使用密钥对其进行签名以检测篡改,他们仍然可以对其进行编辑,但您将知道他们已经这样做了

    您甚至无法设置只读标志,正如此question确认的那样,因为没有只读头,即使您制作了一个符合此头的下载程序,并在文件上设置了标志,用户也可以从文件中删除只读标志并对其进行编辑