iPhone创建带有换行符的.txt文件
我需要将 NSStrings 从数组保存到文档目录中的 .txt 文件中,这是简单的部分。但如何在每个字符串之间放置新的换行符?
我已经尝试过 \n 正如你在下面的代码中看到的那样,在 NSLog 中显示新字符串时效果很好。但是当你在我的电脑上打开 .txt 时,它是连续的一行。我的头现在在转圈,请有人救救我哈哈
NSString *string = [stringArray componentsJoinedByString:@"\n"];
NSLog(@"string: %@",string);
NSData *dataToWrite = [[NSString stringWithFormat:@"%@",string] dataUsingEncoding:NSUTF8StringEncoding];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [docsDirectory stringByAppendingPathComponent:@"myFile.txt"];
[dataToWrite writeToFile:path atomically:YES];
I need to save NSStrings from an array into a .txt file in my documents directory, which is the easy part. but how do I put a new linebreak between each string?
i have already tried \n as you can see in the code below, which works fine when showing the new string in NSLog. But when you open the .txt on my PC it is one continuous line. My head is now spinning in circles, someone please save me lol
NSString *string = [stringArray componentsJoinedByString:@"\n"];
NSLog(@"string: %@",string);
NSData *dataToWrite = [[NSString stringWithFormat:@"%@",string] dataUsingEncoding:NSUTF8StringEncoding];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [docsDirectory stringByAppendingPathComponent:@"myFile.txt"];
[dataToWrite writeToFile:path atomically:YES];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“\n”字符是换行符,但也不会创建回车符。在某些系统(特别是 Unix 系统)上,您只需要换行符即可。然而,在 Windows 计算机上,它经常需要回车符 (\r) 后跟换行符 (\n)
请注意,Windows 上的某些应用程序足够智能,可以仅处理换行符 (\n),而无需回车符 (\r) )并仍然正确显示。例如,我认为虽然记事本不会呈现带有换行符的仅换行符的文档,但写字板却可以。
The "\n" character is a newline, but does not create a carriage return as well. On some systems (Unix systems in particular), a newline is all you need. On Windows machines, however, it frequently expects a carriage return (\r) followed by a newline (\n)
Note that some applications on Windows are smart enough to handle just a newline (\n) character without a carriage return (\r) and still display it correctly. For example, I think that while notepad does NOT render newline-only documents with line breaks, wordpad does.