readline() – read a single line from a text file and return the line as a string.
The file read() method can be used to read the whole text file and return as a single string. The read text can be stored into a variable which will be a string. Alternatively the file content can be read into the string variable by using the with statement which do not requires to close file explicitly.
The readString() method of File Class in Java is used to read contents to the specified file. Return Value: This method returns the content of the file in String format. Note: File. readString() method was introduced in Java 11 and this method is used to read a file's content into String.
To convert an integer to string in Python, use the str() function. This function takes any data type and converts it into a string, including integers. Use the syntax print(str(INT)) to return the int as a str , or string.
NSString *path = [[NSBundle mainBundle] pathForResource:@"NewsStory1" ofType:@"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
See Apple's iOS API documentation for NSString, specifically the section "Creating and Initializing a String from a File"
In swift
let path = NSBundle.mainBundle().pathForResource("home", ofType: "html")
do {
let content = try String(contentsOfFile:path!, encoding: NSUTF8StringEncoding)} catch _ as NSError {}
Very Simple
Just create a method as follows
- (void)customStringFromFile
{
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"NewsStory1" ofType:@"txt"];
NSString *stringContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"\n Result = %@",stringContent);
}
In Swift 4 this can be done like this:
let path = Bundle.main.path(forResource: "test_data", ofType: "txt")
if let path = path {
do {
let content = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
print(content)
} catch let error as NSError {
print("Error occured: \(error.localizedDescription)")
}
} else {
print("Path not available")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With