ios 查找文件大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5743856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding file's size
提问by Kiran
In my iPhone app I am using the following code to find a file's size. Even though the file exists, I am seeing zero for the size. Can anyone help me? Thanks in advance.
在我的 iPhone 应用程序中,我使用以下代码来查找文件的大小。即使文件存在,我也看到大小为零。谁能帮我?提前致谢。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *URL = [documentsDirectory stringByAppendingPathComponent:@"XML/Extras/Approval.xml"];
NSLog(@"URL:%@",URL);
NSError *attributesError = nil;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:URL error:&attributesError];
int fileSize = [fileAttributes fileSize];
回答by Roger
Try this;
尝试这个;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:URL error:&attributesError];
NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
long long fileSize = [fileSizeNumber longLongValue];
Note that the fileSize won't necessarily fit in an integer (especially a signed one) although you could certainly drop to a long for iOS as you'll never exceed that in reality. The example uses long long as in my code I have to be compatible with systems with much larger storage available.
请注意,fileSize 不一定适合整数(尤其是带符号的整数),尽管您肯定可以将 iOS 降为 long,因为实际上您永远不会超过该值。该示例使用 long long 因为在我的代码中我必须与具有更大存储空间的系统兼容。
回答by Krodak
One liner in Swift:
Swift 中的一个班轮:
let fileSize = try! NSFileManager.defaultManager().attributesOfItemAtPath(fileURL.path!)[NSFileSize]!.longLongValue
回答by kelin
If you have a URL
(NSURL
, not a String
), you can get the file size without a FileManager
:
如果您有URL
( NSURL
,而不是String
),则可以在没有 的情况下获取文件大小FileManager
:
let attributes = try? myURL.resourceValues(forKeys: Set([.fileSizeKey]))
let fileSize = attributes?.fileSize // Int?
回答by Hemang
Swift 4.x
斯威夫特 4.x
do {
let fileSize = try (FileManager.default.attributesOfItem(atPath: filePath) as NSDictionary).fileSize()
print(fileSize)
} catch let error {
print(error)
}
回答by Urvish Patel
Get the file size in MBTry This code for swift
获取以MB为单位的文件大小 尝试使用此代码快速
func getSizeOfFile(withPath path:String) -> UInt64?
{
var totalSpace : UInt64?
var dict : [FileAttributeKey : Any]?
do {
dict = try FileManager.default.attributesOfItem(atPath: path)
} catch let error as NSError {
print(error.localizedDescription)
}
if dict != nil {
let fileSystemSizeInBytes = dict![FileAttributeKey.systemSize] as! NSNumber
totalSpace = fileSystemSizeInBytes.uint64Value
return (totalSpace!/1024)/1024
}
return nil
}