ios 读取文本文件并将其转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7235015/
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
Reading a text file and turning it into a string
提问by Marek Sebera
I have added a text file to Xcode, now I want to make a string with it. How do I load it and put it into a string?
我已经向 Xcode 添加了一个文本文件,现在我想用它制作一个字符串。我如何加载它并将其放入字符串中?
NewsStory1.txt
is the file, and I'm using Obj-C.
NewsStory1.txt
是文件,我正在使用 Obj-C。
回答by Marek Sebera
NSString *path = [[NSBundle mainBundle] pathForResource:@"NewsStory1" ofType:@"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
See Apple's iOS API documentation for NSString, specifically the section "Creating and Initializing a String from a File"
请参阅 Apple 的NSString的 iOS API 文档,特别是“Creating and Initializing a String from a File”部分
回答by Hassy
In swift
在迅速
let path = NSBundle.mainBundle().pathForResource("home", ofType: "html")
do {
let content = try String(contentsOfFile:path!, encoding: NSUTF8StringEncoding)} catch _ as NSError {}
回答by Rajesh Loganathan
Very Simple
很简单
Just create a method as follows
只需创建一个方法如下
- (void)customStringFromFile
{
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"NewsStory1" ofType:@"txt"];
NSString *stringContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"\n Result = %@",stringContent);
}
回答by Maxim Makhun
In Swift 4 this can be done like this:
在 Swift 4 中,这可以像这样完成:
let path = Bundle.main.path(forResource: "test_data", ofType: "txt")
if let path = path {
do {
let content = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
print(content)
} catch let error as NSError {
print("Error occured: \(error.localizedDescription)")
}
} else {
print("Path not available")
}