gpt4 book ai didi

xcode - 如何从/Library/Application Support/文件夹中读取内容?

转载 作者:行者123 更新时间:2023-12-03 16:58:01 27 4
gpt4 key购买 nike

我正在制作 OX Cocoa 应用程序,我希望能够在按下按钮时使用该应用程序读取和写入文本文件。这些文本文件应保存在/Library/Application Support/AppName 中,但我无法让我的应用程序从那里读取任何内容。它可以写入该文件夹,但无法读取其中写入的内容,即使我可以在查找器中看到该文件。

这是我正在使用的成功写入文件夹的代码。

    NSString *text = editor.string;
NSString *path = @"/Library/Application Support/";

NSMutableString *mu = [[NSMutableString stringWithString:path] init];
[mu insertString:FileName.stringValue atIndex:mu.length];
[mu insertString:@".txt" atIndex:mu.length];

path = [mu copy];
[text writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];

这是我正在使用(但失败)从文本文件中读取的代码。

    NSArray *path = [[NSBundle mainBundle] pathsForResourcesOfType:@"txt" inDirectory:@"/Library/Application Support/"];
NSString *output = @"";

NSMutableString *mu = [[NSMutableString stringWithString:output] init];

for (int i = 0; i < [path count]; i++) {
NSString *text = [NSString stringWithContentsOfFile:path[i] encoding:NSUTF8StringEncoding error:NULL];
[mu insertString:text atIndex:mu.length];
[mu insertString:@"\n" atIndex:mu.length];
}

[textView setString:mu];

任何关于我可以纠正的提示都会非常有帮助,我有点卡在这里。

编辑:根据您的输入,我已将代码更新为:

    NSString *fileLocation = @"~/Library/Application Support/";
NSArray *text = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:fileLocation error:nil];
NSString *output = @"";
NSMutableString *mu = [[NSMutableString stringWithString:output] init];

for (int i = 0; i < [text count]; i++) {
[mu insertString:text[i] atIndex:mu.length];
[mu insertString:@"\n" atIndex:mu.length];
}
[textView setString:mu];

但是文件中的文本仍然没有出现。

最佳答案

当您对应用程序进行沙箱处理时,大多数硬编码路径都会失败。即使您侥幸逃脱了这个惩罚,或者您不打算将此应用放入沙箱中,这也是一个值得改掉的坏习惯。

此外,您确定要 /Library 而不是 ~/Library 吗?前者通常是用户不可写的。后者位于用户的主目录(或沙盒中的容器)中。

要获取应用程序支持目录、缓存目录或您可能想要在其中创建内容并稍后从中检索它们的任何其他目录,ask a file manager for it .

关于xcode - 如何从/Library/Application Support/文件夹中读取内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14884073/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com