iPhone创建带有换行符的.txt文件

发布于 2024-12-20 20:02:24 字数 657 浏览 2 评论 0原文

我需要将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

驱逐舰岛风号 2024-12-27 20:02:24

“\n”字符是换行符,但也不会创建回车符。在某些系统(特别是 Unix 系统)上,您只需要换行符即可。然而,在 Windows 计算机上,它经常需要回车符 (\r) 后跟换行符 (\n)

NSString *string = [stringArray componentsJoinedByString:@"\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)

NSString *string = [stringArray componentsJoinedByString:@"\r\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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文