gpt4 book ai didi

java - 将文件作为参数传递

转载 作者:行者123 更新时间:2023-11-29 04:04:22 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com