How to Read User Input in Java

Here we will see how to read user inputs in java.Always we can’t hardcode values in java program some scenario requires input dynamically.
Consider wrapping an InputStreamReader within a BufferedReader.
 BufferedReader in
    = new BufferedReader(new InputStreamReader(System.in));  

Example

 import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class BufferedReaderExample {

private String dirName = null;

BufferedReaderExample() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println(“Please enter the directory name:”);

try {
dirName = br.readLine();
if (!dirName.endsWith(“/”)) {
dirName = dirName + “/”;
}

} catch (IOException ioExcption) {
System.out.println(“IO exception occurred!”);
System.exit(1);
}

File dir = new File(dirName);
try {
if (!dir.exists()) {
System.out.println(“Entered directory doesn’t exist”);
} else {
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println(“Files” + files[i]);

}
}
} catch (Exception e) {
// TODO: handle exception
}

}

public static void main(String[] args) {
new BufferedReaderExample();
}

}

About mohan

This is Mohan Jayapalan author of TechPages Blog.I am a part time blogger and Currently working for private Software Concern.

© Copyright 2010-2016 www.techpages.org · All Rights Reserved · Powered by WordPress ·