重命名后Java更新文件引用

时间:2016-04-15 15:21:38

标签: java file legacy-code

您好我处理一些遗留代码时遇到问题。 我需要一种方法来从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对象。但是我必须在我的路上重构一堆方法,所以我需要创建一堆不同的返回对象。

2 个答案:

答案 0 :(得分:-1)

我想到了以下可能性:

  1. 传递一个可变对象,例如一个新的String [1]并将其设置在那里。 (超级丑陋,因为你有副作用,而不是纯粹的功能)(另一方面:你已经有副作用 - 去图; - ))
  2. 使用泛型返回对象,如String [],Map,可在各种实用程序中找到的Pair实现(例如org.colllib.datastruct.Pair)
  3. 使用手工制作的退货对象
  4. 就个人而言,我可能会选择(2),但也可能是(3)

答案 1 :(得分:-1)

据我所知,使用ReturnObjet似乎是唯一的解决方案。

相关问题