Java Stream、File、IO
控制台输入输出、File 类、字节流与字符流的读写。
控制台输出
System.out is standard output: print stays on the line, println breaks it, printf formats. System.err writes to the error stream — send warnings and errors there.
public class ConsoleOut {
public static void main(String[] args) {
System.out.print("no newline ");
System.out.println("then newline");
System.out.printf("%s = %d%n", "count", 3);
System.err.println("this goes to stderr");
}
}no newline then newline
count = 3读取控制台输入
Wrap System.in in a BufferedReader and call readLine(), which returns null at end of input. It is far faster than reading byte by byte but throws IOException.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadConsole {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
if (line == null) {
System.out.println("no input (stdin closed)");
} else {
System.out.println("you typed: " + line);
}
}
}no input (stdin closed)File 类
File represents a path to a file or directory, not its content. Use exists, isFile, isDirectory to classify, getName / getAbsolutePath to inspect, and mkdirs to create parents.
import java.io.File;
import java.io.IOException;
public class FileDemo {
public static void main(String[] args) throws IOException {
File dir = new File("demo_dir");
if (!dir.exists()) {
dir.mkdirs();
}
File f = new File(dir, "a.txt");
if (!f.exists()) {
f.createNewFile();
}
System.out.println(dir.isDirectory());
System.out.println(f.isFile());
System.out.println(f.getName());
System.out.println(f.length() >= 0);
}
}true
true
a.txt
true字节流读写
FileInputStream / FileOutputStream work byte by byte, which suits images and archives. read() returns 0-255, or -1 at end of stream.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStream {
public static void main(String[] args) throws IOException {
try (FileOutputStream out = new FileOutputStream("b.bin")) {
out.write(new byte[]{65, 66, 67});
}
try (FileInputStream in = new FileInputStream("b.bin")) {
int b;
while ((b = in.read()) != -1) {
System.out.print((char) b);
}
}
System.out.println();
}
}ABC字符流读写
FileReader / FileWriter handle characters and encoding for you. Wrap in BufferedReader to get readLine(), or BufferedWriter to get newLine().
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CharStream {
public static void main(String[] args) throws IOException {
try (BufferedWriter w = new BufferedWriter(new FileWriter("c.txt"))) {
w.write("line1");
w.newLine();
w.write("line2");
}
try (BufferedReader r = new BufferedReader(new FileReader("c.txt"))) {
String line;
while ((line = r.readLine()) != null) {
System.out.println(line);
}
}
}
}line1
line2try (resource) is try-with-resources: it closes automatically even on exceptions. Hand-written finally { close(); } is easy to get wrong, so prefer this form.控制台输出
System.out 是标准输出流,print 不换行、println 换行、printf 支持格式化。System.err 输出到错误流,日志和报错应该走它。
public class ConsoleOut {
public static void main(String[] args) {
System.out.print("no newline ");
System.out.println("then newline");
System.out.printf("%s = %d%n", "count", 3);
System.err.println("this goes to stderr");
}
}no newline then newline
count = 3读取控制台输入
BufferedReader 包在 System.in 外层,readLine() 按行读,读到末尾返回 null。它比逐字节读高效得多,但需要处理 IOException。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadConsole {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
if (line == null) {
System.out.println("no input (stdin closed)");
} else {
System.out.println("you typed: " + line);
}
}
}no input (stdin closed)File 类
File 表示文件或目录的路径,不表示内容。exists、isFile、isDirectory 判断类型,getName、getAbsolutePath 取信息,mkdirs 递归建目录。
import java.io.File;
import java.io.IOException;
public class FileDemo {
public static void main(String[] args) throws IOException {
File dir = new File("demo_dir");
if (!dir.exists()) {
dir.mkdirs();
}
File f = new File(dir, "a.txt");
if (!f.exists()) {
f.createNewFile();
}
System.out.println(dir.isDirectory());
System.out.println(f.isFile());
System.out.println(f.getName());
System.out.println(f.length() >= 0);
}
}true
true
a.txt
true字节流读写
FileInputStream / FileOutputStream 按字节读写,适合图片、压缩包等二进制文件。read() 返回 0-255 的整数,读到末尾返回 -1。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStream {
public static void main(String[] args) throws IOException {
try (FileOutputStream out = new FileOutputStream("b.bin")) {
out.write(new byte[]{65, 66, 67});
}
try (FileInputStream in = new FileInputStream("b.bin")) {
int b;
while ((b = in.read()) != -1) {
System.out.print((char) b);
}
}
System.out.println();
}
}ABC字符流读写
FileReader / FileWriter 按字符处理文本,自动处理编码转换。包一层 BufferedReader 能用 readLine(),包 BufferedWriter 能用 newLine()。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CharStream {
public static void main(String[] args) throws IOException {
try (BufferedWriter w = new BufferedWriter(new FileWriter("c.txt"))) {
w.write("line1");
w.newLine();
w.write("line2");
}
try (BufferedReader r = new BufferedReader(new FileReader("c.txt"))) {
String line;
while ((line = r.readLine()) != null) {
System.out.println(line);
}
}
}
}line1
line2try (资源) 是 try-with-resources,块结束自动 close(),即使抛异常也会关。手写 finally { close(); } 容易漏,新代码一律用这种写法。