写入UTF16时iOS导出文件中的额外空格

时间:2012-10-09 15:58:31

标签: objective-c ios

当我从我的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时,它可以正常工作。

感谢。

1 个答案:

答案 0 :(得分:2)

NSUTF16StringEncoding(这是NSUnicodeStringEncoding的别名)在输出前面加上一个所谓的“字节顺序标记”,它由字节“FE FF”或“FF FE”组成,表示以下数据是big-endian还是little-endian UTF-16。

要避免使用字节顺序标记,请使用NSUTF16BigEndianStringEncodingNSUTF16LittleEndianStringEncoding

备注:

的更好选择
[tempFilePath cStringUsingEncoding:NSASCIIStringEncoding]

[tempFilePath fileSystemRepresentation];