关系图
OutputStream例子
package com.alex.examples.exceptions;
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
String data = "中华人民共和国万岁";
OutputStream outputStream = new FileOutputStream("D:\\测试.txt");
//将字符串转换成字节
byte[] bytes = data.getBytes();
//将数据写入输出流
outputStream.write(bytes);
//关闭输出流(一定要记得,用完即关)
outputStream.close();
}
}
InputStream例子
package com.alex.examples.exceptions;
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
String path = "D:\\测试.txt";
// 第1步、使用File类找到一个文件
File f = new File(path); // 声明File对象
// 第2步、通过子类实例化父类对象
InputStream input; // 准备好一个输入的对象
input = new FileInputStream(f); // 通过对象多态性,进行实例化
// 第3步、进行读操作
byte b[] = new byte[1024]; // 所有的内容都读到此数组之中
input.read(b); // 读取内容 网络编程中 read 方法会阻塞
// 第4步、关闭输出流
input.close(); // 关闭输出流
System.out.println("内容为:" + new String(b)); // 把byte数组变为字符串输出
}
}
InputStreamReader例子
package com.alex.examples.exceptions;
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
String path = "D:\\测试.txt";
transReadNoBuf(path);
transReadByBuf(path);
}
public static void transReadNoBuf(String path) throws IOException {
/**
* 没有缓冲区,只能使用read()方法。
*/
InputStreamReader isr = new InputStreamReader(new FileInputStream(path));
char[] cha = new char[1024];
int len = isr.read(cha);
System.out.println(new String(cha, 0, len));
isr.close();
}
public static void transReadByBuf(String path) throws IOException {
/**
* 使用缓冲区 可以使用缓冲区对象的 read() 和 readLine()方法。
*/
BufferedReader bufr = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
String line;
while ((line = bufr.readLine()) != null) {
System.out.println(line);
}
bufr.close();
}
}
OutputStreamWriter例子
package com.alex.examples.exceptions;
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
String path = "D:\\测试.txt";
File f = new File(path);
Writer out = new OutputStreamWriter(new FileOutputStream(f)); // 字节流变为字符流
out.write("hello world!!"); // 使用字符流输出
out.close();
}
}