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;
}
}
}
有什么建议吗
# 1 楼答案
您必须使用以下设置自己的只读属性:
从documentation of the setReadOnly method开始:
# 2 楼答案
不幸的是,这是不可能的
一旦文件位于您无法控制的用户机器上,您就无法强制执行有关该文件的任何内容
您可以使用密钥对其进行签名以检测篡改,他们仍然可以对其进行编辑,但您将知道他们已经这样做了
您甚至无法设置只读标志,正如此question确认的那样,因为没有只读头,即使您制作了一个符合此头的下载程序,并在文件上设置了标志,用户也可以从文件中删除只读标志并对其进行编辑