核心代码
package ioDemo;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class ByteStreamDemo {
public static void main(String[] args) {
out();
in();
}
private static void out() {
try {
File file = new File("C:\\Users\\lihw\\Desktop\\test\\123.txt");
OutputStream os = new FileOutputStream(file);
String info = "小桥流水哗啦啦";
os.write(info.getBytes(StandardCharsets.UTF_8));
os.close();
System.out.println("写完了");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void in(){
try {
File file = new File("C:\\Users\\lihw\\Desktop\\test\\lhw.txt");
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = -1;
StringBuffer sb = new StringBuffer();
while ((len = is.read(bytes)) != -1) {
sb.append(new String(bytes, 0 , len));
}
System.out.println("读取的内容:");
System.out.println(sb.toString());
is.close();
System.out.println("读文本结束了");
} catch (Exception e) {
e.printStackTrace();
}
}
}