您好,我在处理一些遗留代码时遇到问题。 我需要一种方法来获取从 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。 重命名不是问题,但我需要以某种方式将新文件名传递给调用方法。 在现实生活中的问题中,这些方法之间的多个对象之间存在更大的堆栈跟踪。
将文件的更改名称返回到调用层次结构的开头的最佳方法是什么,我可以在其中更改列表中的对象。 我目前最好的猜测是创建一个 ReturnObject,它同时保存要返回的 String 和新的 File 对象。但随后我必须重构一堆方法,因此我需要创建一堆不同的返回对象。
最佳答案
我想到以下可能性:
- 传递一个可变对象,例如一个新的 String[1] 并将其设置在那里。 (非常丑陋,因为你有副作用,不再是一个纯函数)(另一方面:你已经有副作用 - 想想看;-))
- 使用通用返回对象,例如 String[]、Map、Pair 实现,您可以在各种实用程序中找到这些实现(例如 org.colllib.datastruct.Pair)
- 使用手工制作的返回对象
就我个人而言,我可能会选择(2),但也可能是(3)
关于重命名后Java更新文件引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36651050/