Suresh Rohan's Blog

This blog is all about Java, J2EE,Spring, Angular, React JS, NoSQL, Microservices, DevOps, BigData, Tutorials, Tips, Best practice, Interview questions, Views, News, Articles, Techniques, Code Samples, Reference Application and much more

Thursday, June 4, 2015

Java Input and Output


Console Class

- used for reading the data from the console and writing the data on the console.
- obtain a reference to the console using the System.console() method.

// get the System console object
Console console = System.console();

// read a line and print it through printf
console.printf(console.readLine());

String userName = null;
char[] password = null;
userName = console.readLine("Enter your username: ");
// typed characters for password will not be displayed in the screen
password = console.readPassword("Enter password: ");
// password is a char[]: convert it to a String first before


Reader classes


- read the contents in the stream and try interpreting them as characters, such as a tab, end-of-file, newline,

// try opening the file with FileReader
try (FileReader inputFile = new FileReader(file)) {
int ch = 0;
// while there are characters to fetch, read, and print the
// characters when EOF is reached, read() will return −1,
// terminating the loop
while( (ch = inputFile.read()) != −1) {
// ch is of type int - convert it back to char
// before printing
System.out.print( (char)ch );
}

} catch (FileNotFoundException fnfe) {
// the passed file is not found ...
System.err.printf("Cannot open the given file %s ", file);
}
catch(IOException ioe) {
// some IO error occurred when reading the file ...
System.err.printf("Error when processing file %s... skipping it", file);
}
// try-with-resources will automatically release FileReader object


BufferedReader and BufferedWriter

// try opening the source and destination file
// with FileReader and FileWriter
try (BufferedReader inputFile = new BufferedReader(new FileReader(srcFile));
BufferedWriter outputFile = new BufferedWriter(new FileWriter(dstFile))) {
int ch = 0;
// while there are characters to fetch, read the characters from
// source stream and write them to the destination stream
while( (ch = inputFile.read()) != −1) {
// ch is of type int - convert it back to char before
// writing it
outputFile.write( (char)ch );
}
// no need to call flush explicitly for outputFile - the close()
// method will first call flush before closing the outputFile stream
} catch (FileNotFoundException fnfe) {
// the passed file is not found ...
System.err.println("Cannot open the file " + fnfe.getMessage());
}
catch(IOException ioe) {
// some IO error occurred when reading the file ...
System.err.printf("Error when processing file; exiting ... ");
}
// try-with-resources will automatically release FileReader object

No comments:

Post a Comment