用 UIWebView 显示中文文本文件的若干有关问题

用 UIWebView 显示中文文本文件的若干问题

 UIWebView 支持文本文件的显示,你可以使用以下代码加载文本文件:

NSString* path=[[NSBundlemainBundle]pathForResource:@"48_1"ofType:@".txt"];

NSURL* url=[NSURLfileURLWithPath:path];

if(url)

        [_webviewloadRequest:[NSURLRequestrequestWithURL:url]];

很不幸,对于中文,UIWebView支持得并不是很好:

用 UIWebView 显示中文文本文件的若干有关问题

48_1.txt 文件中包含了中文,我们不知道它是什么编码,可能是 UTF8,也可能是 GBK 或 GB18030 。我们可以通过stringWithContentsOfFile 方法推断它的编码:

NSStringEncoding * usedEncoding = nil;

    int encoding;

    // BOM 头的如 utf-8这里会识别

    NSString *body = [NSStringstringWithContentsOfFile:pathusedEncoding:usedEncoding error:nil];

    if (!body)

    {

        //如果之前不能解码,现在使用GBK解码

        NSLog(@"GBK");

        encoding=0x80000632;

        body = [NSStringstringWithContentsOfFile:pathencoding:encoding error:nil];

    }

    if (!body) {

        //再使用GB18030解码

        NSLog(@"GBK18030");

        encoding=0x80000631;

        body = [NSStringstringWithContentsOfFile:pathencoding:encoding error:nil];

    }

   

然后将它们装换为 UTF16 编码并保存到新的文件中:

if (body) {

      url=[NSURLfileURLWithPath:pathForTemporaryFile(path.lastPathComponent)];

        NSData* inData=[body dataUsingEncoding:NSUTF16StringEncoding];

        [inData writeToURL:url atomically:YES];

    }

    else {

        NSLog(@"没有合适的编码");

    }

注意,pathForTemporaryFile 函数是我们自定义的。它实际上将文件指向了“沙盒”的 temp 文件夹。

这样,UIWebView 就能正确显示中文了:

用 UIWebView 显示中文文本文件的若干有关问题

但不知道为什么,UIWebView 在显示文本文件时,会将文件末尾的若干字节显示为方块。这些方块实际上是一些“\0”字符。当我用“文本编辑器”或TextMate 等程序打开 48_1.txt 文件时,这些“\0”字符都不会显示在屏幕上。但在 UIWebView 中,它们却被显示为方块。因此可以在保存文件前加上以下代码:

NSString* findStr=@"\0";

NSRange range=[body rangeOfString:findStr];

if (range.location!=NSNotFound) {

     body=[body substringToIndex:range.location];

}

这样,你就可以把那些方块除掉。