Reading Input from std

Scanner in = new Scanner(System.in);
String name = in.nextline();  // reads a line of input (contain spaces)
String firstName = in.next(); // reads a word (delimited by whitespace)
String age = in.nextInt();    // reads an integer

如果要读密码,用 Console Class

Formatting std Output

printf method from the C library (bookmarked)

a format string can indicate the index of the argument to be formatted.

System.out.printf("%1$s %2$tB %2$te, %2$tY", "Due date:", new Date());
System.out.printf("%s %tB %<te, %<tY", "Due date:", new Date());

The index must immediately follow the %, and it must be terminated by a $. (index start with 1, not 0)

Alternatively, you can use the < flag. It indicates that the same argument as in the preceding format specification should be used again.

like sprintf ➡️Concatenation

formatting date output (bookmarked)

File Input and Output

in

Scanner in = new Scanner(Path.of("myfile.txt"), StandardCharsets.UTF_8);
// "c:\\mydirectory\\myfile.txt"

然后使用 Scanner 的 method 读就完了

❗️注意路径需要 Path.of method。如果按照 output 一样,这将会把这串字符串给了 Scanner

out

PrintWriter out = new PrintWriter("myfile.txt", StandardCharsets.UTF_8);
/* ...... */
out.flush();
out.close();  // 看起来必须有这个才能真的写入

然后可以用 print 之类的操作 (但不是System.out)

如果使用了相对路径

那么起始路径是 java 虚拟机开始的地方

// You can find the directory location with this call:
String dir = System.getProperty("user.dir");