SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
File Processing
Exercise:
Exercises
Question:5 | ISBN:9780136091813 | Edition: 2

Question

Write a method called readEntireFile that accepts a Scanner representing an input file as its parameter, then reads that file and returns its entire text contents as a String.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

// package chap456;

import java.io.FileReader;
import java.io.IOException;

public class ReadEntireFile {

    public static String readEntireFile() throws IOException {

        FileReader in = new FileReader("{give proper path}\\input.txt");

        // use StringBuilder class as we want string to be mutable
        StringBuilder sb = new StringBuilder();

        // it'll stop reading if there is no character which means -1
        while(in.read() != -1) {
            sb.append(in.read());
        }

        // convert it to string and return
        String contents = sb.toString();
        
        in.close();
        return contents;
    }

    public static void main(String[] args) throws IOException {

        System.out.println(readEntireFile());
    }

}

 

0 0

Discussions

Post the discussion to improve the above solution.