实用方法 - 传递文件或字符串? [英] Utility method - Pass a File or String?

查看:184
本文介绍了实用方法 - 传递文件或字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是实用程序方法的示例:

Here's an example of a utility method:

public static Long getFileSize(String fileString) {

    File file = new File(fileString);

    if (file == null || !file.isFile())
        return null;

    return file.length();
}

将String而不是File传递给方法是一种好习惯像这样?一般来说,在制作这种风格的实用方法时应该采用什么推理?

Is it a good practise to pass a String rather than a File to a method like this? In general what reasoning should be applied when making utility methods of this style?

推荐答案

这是我的首选解决方案:

This is my preferred solution:

public static Long getFileSize(String path) {
    return getFileSize(new File(path));
}

public static Long getFileSize(File file) {
    return (!file.isFile()) ? -1L : file.length();
}

注意它返回-1L而不是0L,以允许调用者区分空文件和由于某种原因无法确定长度的文件。在没有长度文件的情况下, file.length()将返回零;例如

Note that it is returning -1L rather than 0L, to allow the caller to distinguish between an empty file, and a "file" whose length cannot be determined for some reason. The file.length() will return zero in some cases where you don't have a zero length file; e.g.


  • 文件不存在时

  • 文件是一个目录

  • 文件是一个特殊的文件(例如设备文件,管道等),操作系统无法确定其长度。

  • when the file does not exist
  • when the file is a directory
  • when the file is a special file (e.g. device file, pipe, etc) and the OS cannot determine its length.

file.isFile()调用处理这些情况。但是,方法是否应该返回 -1L 或抛出异常是有争议的。这场辩论的答案取决于 -1L 案例是正常还是例外,而这只能参考该方法的上下文来确定。旨在使用,

The file.isFile() call deals with these cases. However, it is debatable whether the method(s) should return -1L or throw an exception. The answer to this debate turns on whether the -1L cases are "normal" or "exceptional", and that can only be determined with reference to the contexts in which the method is designed to be used,

这篇关于实用方法 - 传递文件或字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆