Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a text file and turning it into a string

People also ask

Which function can be used to read a text file as a string?

readline() – read a single line from a text file and return the line as a string.

How do I read a text file to a string variable?

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.

How do you read a text file as a string in Java?

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.

How do you convert text to string in Python?

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")
}