I am using the writeToFile:atomically: method to write some encrypted data to a text file. The problem is, the file it needs to be saved as must be the file the user encrypts, with the extension I choose. Here is what I have so far:
[encryptedData writeToFile:[[NSHomeDirectory() stringByAppendingPathComponent:#"Desktop"]
stringByAppendingPathComponent:#"encryptedfile.txt.kry"] atomically:YES];
^//fileName here
As you can see, the encrypted filename is hardcoded as encryptedfile.txt.kry. But say the user selects the file "test.avi" to encrypt, the encrypted file that is written to the desktop should be named test.avi.kry. So there should be ofType:, like in NSBundle. I know there are some NSString methods here that I can use, but have forgotten.
Thanks!
Can't you just append the .kry onto the filename?
If you have the path, and just want the filename, you can use - (NSString *)lastPathComponent:
NSString *filename = [filePath lastPathComponent];
[encryptedData writeToFile:[[NSHomeDirectory() stringByAppendingPathComponent:#"Desktop"]
stringByAppendingPathComponent:[filename stringByAppendingString:#".kry"] atomically:YES];
If you want the filename without the extension you can use - (NSString *)stringByDeletingPathExtension:
NSString *filename = [[filePath lastPathComponent] stringByDeletingPathExtension];
Related
This feels weird, my code goes as simple as
// something like "foo/bar"
NSString *correctFileName = seriesDict[seriesNumber];
if (correctFileName.length > 0)
{
// So I'll have a fileName like "foo/bar.extension" which looks like a directory and a file in it...
NSString *pathExtension = [filePath pathExtension];
NSString *correctFilePath = [[[filePath stringByDeletingLastPathComponent]
stringByAppendingPathComponent:correctFileName]
stringByAppendingPathExtension:pathExtension];
NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:filePath toPath:correctFilePath error:&error];
// And NSFileManager can not treat it as a legal fileName, kind of expected...
if (error)
{
NSLog(#"Rename file at %# failed, error: %#", filePath, error);
}
}
Seems it's ok to rename my file to "foo/bar.extension" in Finder, like this
there might be a solution to do that in code.
If anybody could shred in some light, it'll be highly appreciated.
The / in Finder is converted to a :. / is invalid in POSIX-style paths, while : is invalid in HFS-style paths, so macOS maps those two characters to each other.
The technically correct way would be to create a CFURL using CFURLCreateWithFileSystemPathRelativeToBase specifying kCFURLHFSPathStyle as the path style, and resolving against a base URL you've already created. You'd then copy the path of the full URL using CFURLCopyFileSystemPath.
Pragmatically speaking though, you can simply do a string replace between / and :.
I am really new to saving files in objective C but what I'm trying to accomplish is reading a plist file located in the documents directory on launch or creating it if it doesn't exist.
It should be read in to a NSMutableDictionary. Later on in the app I should be able to save items to the NSMutableDict with categories as keys + text.
The before launch in the viewWillUnload the NSMutableDictionary should be saved into the plist file again.
I have created the plist but I need a way to write to the NSMutableDictionary the right way (category and my result.text string.
And I also need to save the NSMutableDictionary to the plist file and read the plist into the dictionary on launch.
Some help with this would be awsome :D
Thanks guys.
In the savefile void I am doing this:
storeDict = [[ NSMutableDictionary alloc]
init];
[storeDict setObject:resultText.text forKey:#"kvitto"];
[storeDict setObject:kategori forKey:#"kategori"];
[storeDict writeToFile:[self saveFilePath] atomically:YES];
saveFilePath looks like this:
- (NSString *) saveFilePath {
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [[path objectAtIndex:0] stringByAppendingString:#"savefile.plist"];
}
The values are strings collected from a code that the user have scanned so don't worry bout them.
Well so how do I save this correctly keeping the data that already exists in the savefile.plist.
Thanks again
If you want dictionaries and arrays contained in the dictionary to be mutable as well then do the following:
NSData *data = [NSData dataWithContentsOfFile:path];
NSError *error;
storeDict =
[NSPropertyListSerialization
propertyListWithData:data
options:NSPropertyListMutableContainersAndLeaves
format:nil
error: &error];
Why can't you use writeToFile api? Before writing question here you must google or check apple documentation for NSMutableDictionary.
[dict writeToFile:path atomically:YES];
To load saved dictionary
dict = [NSMutableDictionary dictionaryWithContentsOfFile:path];
Happy coding!
I know you can use NSBundle:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"foo" ofType:#"rtf"];
to get the filepath of a file, but how would I get the filename and extension (separately) from the filepath programmatically using NSBundle.
For example, I may have: /Users/theuser/Documents/yourdocument.txt
It is obvious that the file is 'yourdocument', and the extension 'txt'
But I need to get the filename and extension from the filepath to use as an NSString.
Your help is greatly appreciated!
There are methods on NSString that do this. Look at -[NSString pathExtension] and -[NSString lastPathComponent], both defined in NSPathUtilities.h.
to get the filename without extension, try out [NSString stringByDeletingPathExtension];
Try this, it works for me.
NSString *fileName = #"yourFileName.pdf";
NSString *ext = [fileName pathExtension];
i hope this will help you....
Str = [NSString stringWithFormat:#"%#",[openPanel URL]];
[txtBeowsFilePath setStringValue:Str];
Browesfilename=[Str lastPathComponent];
I'm having a problem with a cocoa application that takes the value of a text field, and writes it to a file. The file path is made using stringWithFormat: to combine 2 strings. For some reason it will not create the file and the console says nothing. Here is my code:
//Get the values of the text field
NSString *fileName = [fileNameTextField stringValue];
NSString *username = [usernameTextField stringValue];
//Use stringWithFormat: to create the file path
NSString *filePath = [NSString stringWithFormat:#"~/Library/Application Support/Test/%#.txt", fileName];
//Write the username to filePath
[username writeToFile:filePath atomically:YES];
Thanks for any help
The problem is that you have a tilde ~ in the path. ~ is expanded by the shell to the user's home directory, but this doesn't happen automatically in Cocoa. You want to use -[NSString stringByExpandingTildeInPath]. This should work:
NSString *fileName = [fileNameTextField stringValue];
NSString *username = [usernameTextField stringValue];
NSString *fileName = [fileName stringByAppendingPathExtension:#"txt"]; // Append ".txt" to filename
NSString *filePath = [[#"~/Library/Application Support/Test/" stringByExpandingTildeInPath] stringByAppendingPathComponent:fileName]; // Expand '~' to user's home directory, and then append filename
[username writeToFile:filePath atomically:YES];
Adding to mipadi's reply, it's better to use -[NSString stringByStandardizingPath] since it does more - and can clean up more problems - than resolving the tilde.
I've Declared a string Like so
NSString* fileName = [files objectAtIndex:i];
NSLog(fileName);
NSImage* imageFromBundle = [[NSImage alloc] initWithContentsOfFile:fileName];
and want to use that filename to open a file in a different directory.
I came up with this
NSImage* imageFromBundle2;
imageFromBundle2 = [[NSImage alloc] initWithContentsOfFile:#"/Users/rhaynes/Documents/works4/" filename ];
Any help would be appreciated
I'll assume that your fileName string is actually a file name, like "myImage.png". A lot of the Objective-C docs refer to a file name when they really mean file path - so sometimes it's confusing.
What you want to do is create an NSString that represents the complete path to the file you want to load. For instance, you could say:
NSString * path = [NSString stringWithFormat: #"/Users/rhaynes/Documents/works4/%#", fileName];
That line creates a new NSString using the format string and parameters provided (the %# in the format string indicates that the string value of fileName should be inserted there.) StringWithFormat is a really powerful function, so you should definitely check it out in the docs.
Then you could call initWithContentsOfFile:path, and it should give you the image you want.
NSString* fileName = [files objectAtIndex:i]; NSLog(fileName);
Don't pass non-hard-coded strings as format-string arguments. If they contain format specifiers, you'll get garbage or a crash. (Try this with fileName = #"foo%sbar", for example. Then try it with fileName = #"foo%fbar" for even more fun.)
Your NSLog statement should be:
NSLog(#"%#", fileName);
[I] want to use that filename to open a file in a different directory. I came up with this
NSImage* imageFromBundle2; imageFromBundle2 = [[NSImage alloc] initWithContentsOfFile:#"/Users/rhaynes/Documents/works4/" filename ];
You can only concatenate string literals this way; as you've no doubt seen for yourself, this is a syntax error when one of the strings isn't a literal.
First off, if fileName is actually a pathname, you'll need to use lastPathComponent to get the actual filename. So:
NSString *path = [files objectAtIndex:i];
NSString *filename = [path lastPathComponent];
Then, use stringByAppendingPathComponent: to tack this onto the new superpath.
NSString *desiredFilenamePath = [directoryPath stringByAppendingPathComponent:filename];
Now you have the pathname you wanted to pass to NSImage's initializer.