在UITextView中显示txt文件

时间:2011-10-27 12:50:39

标签: ios nsstring uitextview

我是iPhone开发的新手,需要帮助。我正在开发一个包含UITextView的iPhone应用程序。我在文档中有一个txt文件列表。我正在尝试使用UITextView来显示文本文件的内容,但我无法让它显示任何东西。我使用这些代码希望UITextView显示txt文件:

  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
self.frlistName2 = [[manager contentsOfDirectoryAtPath:documentsDirectoryPath error:nil]pathsMatchingExtensions:[NSArray arrayWithObject:@"txt"]];
NSString *obj = @".txt";
frlisturls2 = [[NSMutableArray alloc] initWithObjects:nil];
NSString *temp;
NSMutableString *mp3Path = [[NSMutableArray alloc] init];
int j =0;
for(int i =0 ; i< [frlistName2 count]; i++)
{
    mp3Path  = [NSMutableString stringWithString:documentsDirectoryPath];
    [mp3Path appendString:@"/"];

    temp = [frlistName2 objectAtIndex:i];
    if([temp hasSuffix :obj])
    {
        [mp3Path appendString: temp];
        [frlisturls2 addObject: mp3Path];
        j++;
    }
    [mp3Path release];
}
NSLog(@"frlisturls2 is%@:",frlisturls2);
[super viewDidLoad];
fileName = [[NSString alloc]init];
fileName=[frlisturls2 objectAtIndex:iRow ];
NSLog(@"the fileName is %@",fileName);
stringSources = [NSString stringWithContentsOfFile: fileName encoding:NSUTF8StringEncoding error:nil];
frtextview=[[UITextView alloc]init];
[frtextview setText:stringSources];
NSLog(@"the file is :%@",stringSources);

文件名显示正确的URL,但是stringSource没有单词。很长的帖子!我希望对你有帮助!

1 个答案:

答案 0 :(得分:1)

这就是我将txt文件读取到txtView的方式

但有时文件编辑器无法打开文件,

NSString *filePath = @"Users/macbookpro/Library/Application
 Support/iPhone Simulator/4.3.2/Applications/ ...
 /Documents/sample.txt"; 
NSString *txtContent = [[NSString alloc]
                                    initWithContentsOfFile:filePath
                                    encoding:NSUTF8StringEncoding
                                    error:&error];

将txtContent加载到textView.text