[英]Java updating file reference after renaming
嗨,我在处理一些旧代码时遇到问题。 我需要一种方法来从parseFile()方法获取更改的文件,直至调用doWithFileList()方法。
public static void main(String[] args) throws IOException {
File file1 = File.createTempFile("file1", ".tmp");
File file2 = File.createTempFile("file2", ".tmp");
ArrayList<File> fileList = new ArrayList<File>();
fileList.add(file1);
fileList.add(file2);
doWithFileList(fileList);
}
static void doWithFileList(List<File> fileList) {
for (File file : fileList) {
String result = parseFile(file);
}
//Do something with the (now incorrect) file objects
for (File file : fileList) {
// always false here
if (!file.exists()) {
System.out.println("File does not exist anymore");
}
}
}
private static String parseFile(File file) {
//1. Get information from the File
//2. Use this information to load an object from the Database
//3. return some property of this object
//4. depending on another property of the DB object rename the file
file.renameTo(new File(file.getAbsoluteFile() + ".renamed"));
return "valueParsedFromFile";
}
我知道File对象是不可变的。 问题是在我的现实世界问题中,parseFile()方法目前仅执行步骤1-3,但我需要添加步骤4。重命名不是问题,但我需要以某种方式获取新文件名。调用方法。 在现实生活中,这些方法之间存在跨越多个对象的较大堆栈跟踪。
将文件的更改名称返回到调用层次结构的开始的最佳方法是什么,在该层次结构中我可以更改列表中的对象。 目前,我最好的猜测是创建一个同时包含要返回的String和新的File对象的ReturnObject。 但是随后我必须在重构过程中重构一堆方法,因此我需要创建一堆不同的返回对象。
我想到以下可能性:
就个人而言,我可能会选择(2),但也可能是(3)
据我所知,使用ReturnObjet
似乎是唯一的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.