1

当我从我的 iPhone 应用程序中将一个简单的文本文件保存为 NSUTF16StringEncoding 时,似乎喜欢在我添加的每一行的开头添加一个额外的“空格”。这是一些粗略的代码,详细说明了我在做什么(不准确,不一定按原样可执行)。

NSArray *paths          = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *tempPath      = [paths objectAtIndex:0];
NSString *tempFilename  = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
NSString *tempFilePath  = [tempPath stringByAppendingPathComponent:tempFilename];
NSError *error;

freopen([tempFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:tempFilePath];

NSString *testLine1 = @"test row 1";
[fileHandle seekToEndOfFile];
[fileHandle writeData:[testLine1 dataUsingEncoding:NSUTF16StringEncoding]]; // NSUTF8StringEncoding

NSString *testLine2 = @"test row 2";
[fileHandle seekToEndOfFile];
[fileHandle writeData:[testLine2 dataUsingEncoding:NSUTF16StringEncoding]]; // NSUTF8StringEncoding

NSString *testLine3 = @"test row 3";
[fileHandle seekToEndOfFile];
[fileHandle writeData:[testLine3 dataUsingEncoding:NSUTF16StringEncoding]]; // NSUTF8StringEncoding

[fileHandle closeFile];  

// convert csv text to data
NSData *dataCsvOutput = [NSData dataWithContentsOfFile:tempFilePath];

NSArray *objects  = [NSArray arrayWithObjects:dataCsvOutput, exportFilename, deviceType, nil];        
NSArray *keys     = [NSArray arrayWithObjects:@"data", @"filename", @"devicetype", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects 
                                                   forKeys:keys];            

NSString  *exportFilename = [withDictionary objectForKey:@"filename"];
NSData    *dataCsvOutput  = [withDictionary objectForKey:@"data"];
NSString  *deviceType     = [withDictionary objectForKey:@"devicetype"];

MFMailComposeViewController *mfViewController = [[MFMailComposeViewController alloc] init];
mfViewController.mailComposeDelegate          = self;
[mfViewController setSubject:@"Test"];
[mfViewController setMessageBody:[NSString stringWithFormat:@"Please find data attached."] isHTML:NO];
[mfViewController addAttachmentData:dataCsvOutput mimeType:@"text/plain;charset=utf-16" fileName:exportFilename];
[self presentModalViewController:mfViewController animated:YES];
[mfViewController release];  

生成的文本文件最终类似于:

测试行 1
 测试行 2
 测试行 3

谁能建议这是为什么?导出为 UTF-8 时它工作正常。

谢谢。

4

1 回答 1

2

NSUTF16StringEncoding(它是 的别名NSUnicodeStringEncoding)在输出前添加一个所谓的“字节顺序标记”,它由字节“FE FF”或“FF FE”组成,并指示以下数据是大端还是小端UTF-16。

To avoid the byte-order marker, use either NSUTF16BigEndianStringEncoding or NSUTF16LittleEndianStringEncoding.

Remark: A better alternative for

[tempFilePath cStringUsingEncoding:NSASCIIStringEncoding]

is

[tempFilePath fileSystemRepresentation];
于 2012-10-09T17:24:15.190 回答