How to read a String value in java programming?

There are three ways to read the string value in java programming.

Buffered Reader: The most basic and common way to read the string value is through the Buffered Reader. The below statements will help in reading.

import java.io.*;
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

String name=in.readLine();

Apache Commons: Aside from Buffered Reader, the apache commons will aid in reading the string value. For this purpose, Apache commons made use of elegant facilities that creates easy to read and cleaner codes. For example:

12

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

package com.howtodoinjava.demo.io; 

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.StringWriter;

 

import org.apache.commons.io.IOUtils;

 

public class ReadStreamIntoStringUsingIOUtils

{

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

{

//Method 1 IOUtils.copy()

StringWriter writer = new StringWriter();

IOUtils.copy(new FileInputStream(new File(“C:/temp/test.txt”)), writer, “UTF-8”);

String theString = writer.toString();

System.out.println(theString);

//Method 2 IOUtils.toString()

String theString2 = IOUtils.toString(new FileInputStream(new File(“C:/temp/test.txt”)), “UTF-8”);

System.out.println(theString2);

}

}

Scanner class: On the other hand, the Scanner class can be used. This is a fresh way to read the string value in Java Programming.

import java.util.*;
Scanner sc=new Scanner(System.in);
String name=sc.nextLine();

You can check programming questions and answers and find any programming solutions you need with our help.