我和我的同事正在争论 File.delete() 方法在 Java 中的工作原理。
在我们的代码中:
File outFile = new File("/dir/name.ext");
if(outFile.exists())
outFile.delete();
FileInputStream inStream = new FileInputStream(outFile);
WriteFile.writeFile(inStream); // Writes the actual file
出于安全原因,我不能在此处包含 writeFile 的整个方法体,但在创建所需的数据库对象后,它会执行以下操作:
BufferedOutputStream out = null;
Object[] args = {"an_encrypted_data_clob_name_in_the_database"};
Class[] argTypes = {Class.forName("java.lang.String")};
Object result = WSCallHelper.jdbcCall(null, rs, "getCLOB", args, argTypes);
CLOB clob = (CLOB)result;
out = new BufferedOutputStream(clob.getAsciiOutputStream());
byte[] buffer = new byte[512];
int bytesRead = -1;
while((bytesRead = inStream.read(buffer)) > -1)
out.write(buffer, 0, bytesRead);
我知道这有点不清楚,但它的一般要点是它创建了 Clob 的 AsciiOutputStream(是的,它应该是一个 Clob ) 并将其写入从先前方法传递的 inStream 对象。
由于 File.delete(); 方法,他们确信这不会写入文件目录,但我确实知道昨天那个位置有一个文件,并且此代码今天运行并在该确切位置写入了一个文件。因为,虽然实际的 file 被删除了,但是那个文件所在位置的 pointer 仍然在 outFile 中,而 的创建inStream 和 outFile 使 inStream 指向该位置。
有什么理由相信在这种情况下不会写入此文件?理想情况下,我想要一些证据证明 delete() 方法删除了 File 对象指向 的文件,而不是指针本身。
最佳答案
java.io.File不是文件指针,也不包含文件指针。它是一个不可变的路径名。
An abstract representation of file and directory pathnames.
Instances of this class may or may not denote an actual file-system object such as a file or a directory.
Instances of the
Fileclass are immutable; that is, once created, the abstract pathname represented by aFileobject will never change.
与 the source code for File ,我们可以看到它是 String 的包装器。
delete无法删除文件指针,因为没有文件指针。
Deletes the file or directory denoted by this abstract pathname.
打开文件的连接由 java.io.FileDescriptor 表示:
Instances of the file descriptor class serve as an opaque handle to the underlying machine-specific structure representing an open file […].
这是输入/输出流与文件系统交互的方式,而不是通过 File,例如 FileOutputStream(File)解释如下:
Creates a file output stream to write to the file represented by the specified
Fileobject. A newFileDescriptorobject is created to represent this file connection.If the file […] does not exist but cannot be created, or cannot be opened for any other reason then a
FileNotFoundExceptionis thrown.
我们可以观察到,例如,the constructor for FileOutputStream委托(delegate)给 File 的路径 String,检查它是否有效,然后丢弃 File:
public FileOutputStream(File file, boolean append)
throws FileNotFoundException
{
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(name);
}
if (name == null) {
throw new NullPointerException();
}
if (file.isInvalid()) {
throw new FileNotFoundException("Invalid file path");
}
this.fd = new FileDescriptor();
fd.attach(this);
this.append = append;
open(name, append);
}
没有文档支持 java.io.File 表示文件指针的想法。 ; )
我们还知道,打开的文件句柄是一种必须在某个时候释放的资源,但是 File 没有提供这样做的方法;因此,File 不符合我们对文件指针应该是什么的概念。
关于java - File.delete() 是否删除 File 对象的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29437078/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为
查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信
从给定URL下载文件并立即将其上传到AmazonS3的更直接的方法是什么(+将有关文件的一些信息保存到数据库中,例如名称、大小等)?现在,我既不使用Paperclip,也不使用Carrierwave。谢谢 最佳答案 简单明了:require'open-uri'require's3'amazon=S3::Service.new(access_key_id:'KEY',secret_access_key:'KEY')bucket=amazon.buckets.find('image_storage')url='http://www.ex
这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife
我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳