Hi i am trying to save text values as binary file and read from that file. i am using following code, i got the binary file in documents directory but when reading data from file only got some numbers please kindly help its urgent.
For writing
NSString *documentsDirectoryPath = [self performSelector:#selector(tempDirectoryPath:) withObject:fileName_];
NSLog(#"%#",documentsDirectoryPath);
if ([[NSFileManager defaultManager] isWritableFileAtPath:documentsDirectoryPath]) {
NSLog(#"content =%#",data_);
[data_ writeToFile:documentsDirectoryPath atomically:YES];
return YES;
}
For reading i use the following code,
NSString *documentsDirectoryPath = [self performSelector:#selector(tempDirectoryPath:) withObject:fileName_];
if ([[NSFileManager defaultManager] isReadableFileAtPath:documentsDirectoryPath]) {
NSMutableData *data_ = [NSMutableData dataWithContentsOfFile:documentsDirectoryPath];
return data_;
}
I got only numbers from the data_ .
How to read the .bin file correctly.?
I got the .bin file when extract get .bin.cpgz file.I can't open the file what is the reason ?Is anything wrong in code?
I am pass string in this way:
[self writeData:#"test string is here" toFile:#"mf.bin"];
Thanks.
It's a little late, but something like this might help you:
http://snippets.aktagon.com/snippets/475-How-to-use-NSKeyedArchiver-to-store-user-settings-on-the-iPhone
Sounds like you need to convert the data into something readable.
NSString *myFile = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
This assumes originally the data you wrote was a NSString, if it was an object you would have to use the appropriate methods for that object.
Related
I want to write data to a .txt file without replacing its older contents.I have moved the file from the NSMainBundle to the documents directory.I am able to write the the file by using the code
NSData *data=[NSKeyedArchiver archivedDataWithRootObject:recentMainArray];
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
[myHandle seekToEndOfFile];
[myHandle writeData:data];
[myHandle closeFile];
But when i try to display the contents of the file,i don't have any data in that.File exists in that path also.This is the following code i use to display the contents.
NSFileManager *manager = [NSFileManager defaultManager];
//filePath - > the documents directory file path
if([manager fileExistsAtPath:filePath]) {
NSMutableArray *savedArray = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
NSMutableArray *storedRecentID = [savedArray objectAtIndex:0];
NSMutableArray *storedRecentName = [savedArray objectAtIndex:1];
NSLog(#"ID:%#",[savedArray objectAtIndex:0]);
NSLog(#"Name:%#",[savedArray objectAtIndex:1]);
}
else {
NSLog(#"file not found, save something to create the file");
}
"null" which is printed as result for those two nslogs.
Please anybody let me know a solution for this problem.FYI,i am using a simulator to test,is this creating a problem.Please suggest me a solution.I have searched a lot and i am not able to find a solution.
Thank you all in advance
Read the data into some Mutable structure (dictionary, array, string) and then append your new data into the same satring. Now write the data into the same path. So the new appended data will be written in file.
I am attempting to create a .xml file and set the contents of the file to equal a predetermined string.
I have built the XML and am currently storing it in an NSString.
I want to put the contents of this string into a file with the extension of .xml and send an email with the file as an attachment.
I am able to email PDFs and assumed creating the file with an extension of .xml would be the easy bit, but alas I cannot do it.
If anyone could offer a helping hand I would be much appreciative.
Try something like this:
NSString *path = ...;
NSString *string = ...;
NSError *error;
BOOL ok = [string writeToFile:path atomically:YES encoding:NSUnicodeStringEncoding error:&error];
if (!ok) {
// an error occurred
NSLog(#"Error writing file at %#\n%#",path, [error localizedFailureReason]);
// implementation continues ..
Writing to Files and URLs
I need to parse a XML file which is located on my server and return the node values without ever downloading the file to the device. Right now, the file is downloading to the device for testing purposes. Here is my current code:
+ (NSString *)dataFilePath:(BOOL)forSave {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentsPath = [documentsDirectory stringByAppendingPathComponent:#"file.xml"];
return documentsPath;
}
+ (NSString *)parse:(NSString *)nodesForPath:(NSString *)elementsForName {
NSString *filePath = [self dataFilePath:FALSE];
NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:filePath];
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
if (doc == nil) { return nil; }
ViewController *view = [[[ViewController alloc] init] autorelease];
NSArray *getVersionInfo = [doc nodesForXPath:nodesForPath error:nil];
for (GDataXMLElement *versionInfo in getVersionInfo) {
NSArray *elm1 = [versionInfo elementsForName:elementsForName];
GDataXMLElement *elm2 = (GDataXMLElement *) [elm1 objectAtIndex:0];
return elm2.stringValue;
}
[doc release];
[xmlData release];
}
It works fine but it parses the file in the document's directory. How would I set it up to parse directly from the web server? Thanks
The only way I can see to do this would be to run a program on the server to parse the file and return the result to the phone.
For the phone to run the code that parses the file it has to read the file which, by definition, will download it.
You could try using a pull parser for the XML and just work with the data received from the network as a stream, discarding unneeded contents.
You read a few bytes from the response, parse them, process, discard, read some more. You might have to make your own implementation of a pull parser because your dealing with incomplete, hence invalid, XML or to look up a parser that's tolerant to data ending (definitely not a validating one).
It might be worth-while to make your own implementation for the parser if you are dealing with really huge XML files. This way you can only store pieces of the XML that you need (you might need part of the XML 'tree' or none at all or you might need to retain other nodes referenced by another node in your XML).
I'm sorry for the generic answer, but I haven't used XML parsers on iOS yet and I'm not anywhere near a Mac atm to be able to test if NSXMLParser works for you.
Edit: Related post here.
Even if you don't want to save the file to your hard disk, you must have the contents of that file loaded on your RAM.
Convert NSData* to NSString, and then NSString to char* and give that to RapidXML.
I am using Dave DeLong's CHCSVParser to parse a csv. I can parse the csv locally, but I cannot get it load a remote csv file. I have been staring at my MacBook way too long today and the answer is right in front of me. Here is my code:
NSString *urlStr = [[NSString alloc] initWithFormat:#"http://www.somewhere.com/LunchSpecials.csv"];
NSURL *lunchFileURL = [NSURL URLWithString:urlStr];
NSStringEncoding encoding = 0;
CHCSVParser *p = [[CHCSVParser alloc] initWithContentsOfCSVFile:[lunchFileURL path] usedEncoding:&encoding error:nil];
[p setParserDelegate:self];
[p parse];
[p release];
Thanks for any help that someone can give me.
-[NSURL path] is not doing what you're expecting.
If I have the URL http://stackoverflow.com/questions/4636428, then it's -path is /questions/4636428. When you pass that path to CHCSVParser, it's going to try and open that path on the local system. Since that file doesn't exist, you won't be able to open it.
What you need to do (as Walter points out) is download the CSV file locally, and then open it. You can download the file in several different ways (+[NSString stringWithContentsOfURL:...], NSURLConnection, etc). Once you've got either the file saved locally to disk or the string of CSV in memory, you can then pass it to the parser.
If this is a very big file, then you'll want to alloc/init a CHCSVParser with the path to the local copy of the CSV file. The parser will then read through it bit by bit and tell you what it finds via the delegate callbacks.
If the CSV file isn't very big, then you can do:
NSString * csv = ...; //the NSString containing the contents of the CSV file
NSArray * rows = [csv CSVComponents];
That will return an NSArray of NSArrays of NSStrings.
Similar to this last approach is using the NSArray category method:
NSString * csv = ...;
NSError * error = nil;
NSArray * rows = [NSArray arrayWithContentsOfCSVString:csv encoding:[csv fastestEncoding] error:&error];
This will return the same structure (an NSArray of NSArrays of NSStrings), but it will also provide you with an NSError object if it encounters a syntax error in the CSV file (ie, malformed CSV).
I think you need an NSString, not an NSURL object to pass to the parser so the extra part you are doing with changing the NSString to an NSURL is the issue. Looking at the CHCSVParser documentation, it looks like he wants NSString in the init.
So maybe you could do something like:
NSError *err = [[[NSError alloc] init] autorelease];
NSString *lunchFileURL = [[NSString stringWithFormat:#"http://www.somewhere.com/LunchSpecials.csv"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *lunchFile = [NSString stringWithContentsOfURL:[NSURL URLWithString:lunchFileURL] encoding:NSUTF8StringEncoding error:&err];
CHCSVParser *p = [[CHCSVParser alloc] initWithContentsOfCSVString:lunchFile usedEncoding:&encoding error:nil];
i m creating an application which makes the iphone work as a pendrive for easy file sharing purpose.
In the first stage, i have some files(png, pdf, jpg, zip) in a directory and i made them display in the tableview in the form of mutable array. It displays in the tableView as shown below,
.DS_Store
.localized
gazelle.pdf
Hamburger_sandwich.jpg
IITD TAJ Picture 028_jpg.jpg
iya_logo_final_b&w.jpg
manifesto09-eng.pdf
RSSReader.sql
SimpleURLConnections.zip
SQLTutorial
I just want to display the name of the files and i do not want to display the extensions. I know that it is possible to extract the extensions of a file in NSFileManager. But i do not know how. Please help me to make my table view look like this
.DS_Store
.localized
gazelle
Hamburger_sandwich
IITD TAJ Picture 028_jpg
iya_logo_final_b&w
manifesto09-eng
RSSReader
SimpleURLConnections
SQLTutorial
In the second stage i have a detailedViewController which takes displays the detailed view of the file like
file size
file type
if it is a image, it should open in imageView
if it is a song, it should play it
So i need to retrive the properties like filePath, fileType, fileSize.. of each files. Please guide me with a tutorial if possible. I too do not have any idea how to convert a mutableArray to a NSString and call the methods like stringByDeletingPathExtension. Please help me. I can even send my source code if needed. If possible, guide me with some example codes and tutorial.
This should work:)
This will get all files in a directory in a NSString *parentDirectory, get its size, if image do something otherwise it assumes is a sound file
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *filePaths = [fm contentsOfDirectoryAtPath:parentDirectory error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
error = nil;
}
for (NSString *filePath in filePaths) {
//filename without extension
NSString *fileWithoutExtension = [[filePath lastPathComponent] stringByDeletingPathExtension];
//file size
unsigned long long s = [[fm attributesOfItemAtPath:[parentDirectory stringByAppendingPathComponent:filePath]
error:NULL] fileSize];
UIImage *image = [UIImage imageNamed:[parentDirectory stringByAppendingPathComponent:filePath];];
//if image...
if(image){
//show it here
}
else{
//otherwise it should be music then, play it using AVFoundation or AudioToolBox
}
}
I hope you will have the file name in NSURL object, if so then you can use the following code to get just the file name and can remove the file extension from the string.
NSArray *fileName = [[fileURL lastPathComponent] componentsSeparatedByString:#"."];
NSLog(#"%#",[fileName objectAtIndex:0]);