Sunday, April 1, 2018

Java I/O basics - easy ways

Read from console (IDE compatible):

Scanner scanner = new Scanner(System.in);

System.out.print("Enter your nationality: ");
String nationality = scanner.nextLine();

// automatically parse primitives:
System.out.print("Enter your age: ");
int age = scanner.nextInt();
Source: CodeJava: 3 ways for reading input from the user in the console
Testing: StackOverflow: Unit testing for user input using Scanner

Write to console:

System.out.println("Some string..."); // with automatic line break
System.out.print("Some string..."); // no line break added
Source: Oracle docs
Testing: StackOverflow: JUnit test for System.out.println()

Read all lines from a file (java.nio):

List lines = Files.readAllLines(Paths.get("input.txt"));
Source: Java2S.com, example in my previous post

Write all lines to a file (java.nio):

Files.write(Paths.get("output.txt"), lines);
Source: Java2S.comexample in my previous post

No comments:

Post a Comment