JAVA IO流知识点全总结
Java IO流是Java进行数据输入输出操作的重要部分,以下是一些常见的IO流知识点及其简单解释和示例代码:
字节流
InputStream
和OutputStream
示例代码:
InputStream is = new FileInputStream("file.txt"); int byteContent; while ((byteContent = is.read()) != -1) { // 处理读取的字节 } is.close(); OutputStream os = new FileOutputStream("file.txt"); String content = "Hello, World!"; os.write(content.getBytes()); os.close();
字符流
Reader
和Writer
示例代码:
Reader reader = new FileReader("file.txt"); int charContent; while ((charContent = reader.read()) != -1) { // 处理读取的字符 } reader.close(); Writer writer = new FileWriter("file.txt"); String content = "Hello, World!"; writer.write(content); writer.close();
缓冲流
BufferedInputStream
,BufferedOutputStream
,BufferedReader
,BufferedWriter
示例代码:
BufferedReader reader = new BufferedReader(new FileReader("file.txt")); String line; while ((line = reader.readLine()) != null) { // 处理读取的行 } reader.close(); BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt")); writer.write("Hello, World!"); writer.close();
对象流
ObjectInputStream
,ObjectOutputStream
示例代码:
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.txt")); oos.writeObject(new MyClass()); oos.close(); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.txt")); MyClass myObject = (MyClass) ois.readObject(); ois.close();
标准输入输出流
System.in
,System.out
,System.err
示例代码:
Scanner scanner = new Scanner(System.in); System.out.println("请输入内容:"); String content = scanner.nextLine(); System.out.println("您输入的内容是:" + content); scanner.close();
文件流
FileInputStream
,FileOutputStream
,FileReader
,FileWriter
- 示例代码已在字节流和字符流部分给出。
数据流
DataInputStream
,DataOutputStream
示例代码:
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt")); dos.writeDouble(123.456); dos.writeInt(789); dos.close();
评论已关闭