java - 将文件作为参数传递

标签 java file oop refactoring parameter-passing

我创建了一个示例来介绍我的问题。

public class Algorithm
{
    // This is the best, but circumstances prevent me from doing this.
    /*public static void computeSomething(Data data)
    {
        // Compute some stuff
    }*/

    public static void computeSomething(DataFileReader reader) throws IOException
    {
        // Compute some stuff.
    }

    public static void computeSomething(File file) throws IOException, DataFormatException
    {
        DataFileReader = DataFileReaderFactory.newDataFileReader(file);

        // Compute some stuff.
    }
}

public class DataFileReaderFactory
{
    private enum FileExtension { XML, UNSUPPORTED_EXTENSION }

    private static final String XMLExtension = ".xml";

    public static DataFileReader newDataFileReader(File file) throws DataFormatException
    {
        switch(computeFileExtension(file))
        {
            case XML :  return new XMLFileReader(file);

            default :   throw new DataFormatException();
        }
    }

    private static FileExtension computeFileExtension(File file)
    {
        if(file.getName().endsWith(XMLExtension))
            return FileExtension.XML;
        else
            return FileExtension.UNSUPPORTED_EXTENSION;
    }
}

所以,我想知道我是否应该定义我的接口(interface)来获取文件,或者我自己的文件阅读器,以确保数据的格式有效。显然,我希望能够将数据本身作为一个Data 对象,但我在这方面受限。原因与数据非常大有关,我必须为多个对象序列化它。在这种情况下,发送数据路径而不是数据本身更为实际。

无论如何,关于这个问题,我倾向于采用 Java 的 File 实例 的方法,因为它看起来更通用,但我想听听您的建议。谢谢!

最佳答案

使用允许您在内存中创建测试程序的东西。例如。使用 InputStream 而不是 File,允许您为测试编写一个简单的 InputStream 实现,而不必在文件系统上创建一个文件,将内容放入其中,并在完成后将其删除。

如果您有一个用于获取数据对象的接口(interface),在我看来这将是最好的。

关于java - 将文件作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1060793/

相关文章:

c++ - 如何比较类中的两个对象(调用对象和参数)?

design-patterns - DDD聚合与GoF的外观

java - 有没有办法从 SharePoint 检索没有文件名的文件?

java while循环内存泄漏

c - 读取 .ini 文件并在 C 中返回特定值

java - 1 次测试运行后无法读取文件,org.apache.poi.EmptyFileException : The supplied file was empty (zero bytes long)

c - 编写一个程序来读取排序并写入数组

c++ - C++ 中的面向对象、继承和组合

java - 我得到下一个输出 :The class 'misBeans.Datos' does not have a readable property 'enlace'

java - 使用Java从https获取图像