我遇到的问题与此问题的发帖人完全相同: Ruby (Errno::EACCES) on File.delete。与他不同的是,为他提供的解决方案中的更改对我不起作用。
这是我的代码,它是一种压缩算法,我想删除原始文件:
uncompressed_file = File.new(Rails.root + filepath)
compressed_file = File.new(Rails.root + "#{filepath[0..filepath.size - 1]}.gz", "w+b")
file_writer = Zlib::GzipWriter.new(compressed_file)
buf = ""
File.open(uncompressed_file, "rb") do | uncompressed |
while uncompressed.read(4096, buf)
file_writer << buf
end
file_writer.close
end
begin
files_changed_by_chmod = File.chmod(0777, uncompressed_file)
rescue
puts "Something happened"
end
puts "Number of files changed by CHMOD : " + files_changed_by_chmod.to_s
File.delete(uncompressed_file)
File.rename(Rails.root + "#{filepath[0..filepath.size - 1]}.gz", Rails.root + filepath)
您会注意到那里有一对夫妇puts
来确认 chmod 发生了什么。输出是这样的:
Number of files changed by CHMOD : 1
而且没有Something happened
。因此运行 chmod 不会产生错误,并且 chmod 确实修改了一个文件(大概是uncompressed_file
.)但是,我仍然在删除行上收到 Errno::EACCESS 错误。
为什么我不能删除文件?!它把我逼到了墙角。我正在运行 Windows 8 和 ruby 1.9.3。
编辑:下面的第一个答案解决了无法删除文件的问题;但是,它使我的代码尝试执行的工作无效(即,当我的文件通过解决方案中提供的压缩算法然后我的其他算法运行时,文件返回损坏)。是的,我也曾尝试在我的通货膨胀方法中模仿这里的编码风格,但这并没有帮助。以下是对我的文件执行加密、解密和解压缩的其余代码:
def inflate_attachment(filepath)
compressed_file = File.new(Rails.root + filepath)
File.open(compressed_file, "rb") do | compressed |
File.open(Rails.root + "#{filepath[0..filepath.size - 7]}_FULL.enc", 'w+b') do | decompressed |
gz = Zlib::GzipReader.new(compressed)
result = gz.read
decompressed.write(result)
gz.close
end
end
end
def encrypt_attachment(filepath, cipher)
unencrypted_file = File.new(Rails.root + filepath)
encrypted_file = File.new(Rails.root + "#{filepath[0..filepath.size - 1]}.enc", "w")
buf = ""
File.open(encrypted_file, "wb") do |outf|
File.open(unencrypted_file, "rb") do |inf|
while inf.read(4096, buf)
outf << cipher.update(buf)
end
outf << cipher.final
end
end
end
def decrypt_attachment(filepath, key, iv)
cipher = OpenSSL::Cipher.new(ENCRYPTION_TYPE)
cipher.decrypt
cipher.key = key
cipher.iv = iv
encrypted_file = File.new(Rails.root + filepath)
decrypted_file = File.new(Rails.root + "#{filepath[0..filepath.size - 5]}.dec", "w")
buf = ""
File.open(decrypted_file, "wb") do |outf|
File.open(encrypted_file, "rb") do |inf|
while inf.read(4096, buf)
outf << cipher.update(buf)
end
outf << cipher.final
end
end
end