Java Stream、File、IO

控制台输入输出、File 类、字节流与字符流的读写。

Intermediate
Key Points字节流处理二进制(InputStream/OutputStream),字符流处理文本(Reader/Writer);流用完必须关闭,用 try-with-resources 最稳。

控制台输出

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.

Java
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");
    }
}
Output
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.

Java
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);
        }
    }
}
Output
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.

Java
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);
    }
}
Output
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.

Java
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();
    }
}
Output
ABC

字符流读写

FileReader / FileWriter handle characters and encoding for you. Wrap in BufferedReader to get readLine(), or BufferedWriter to get newLine().

Java
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);
            }
        }
    }
}
Output
line1
line2
try (resource) is try-with-resources: it closes automatically even on exceptions. Hand-written finally { close(); } is easy to get wrong, so prefer this form.

Friends & Partners