1.使用File打开文件——>2.使用输入或输出流关联文件——>3.进行读写操作——>4.关闭流
package cn.zzx.file;
import java.io.*;
public class StreamDome {
public static void main(String[] args) throws Exception {
//输出流向中写入数据
File file =new File("D:"+File.separator+"demo.txt");
if(!file.exists()){
file.createNewFile(); //创建一个新文件
}
//使用输出流关联文件
OutputStream s = new FileOutputStream(file);
String str = "nwe file!";
//进行写操作
s.write(str.getBytes());
//关闭流
s.close();
//字节输入流
InputStream i = new FileInputStream(file);
byte [] b = new byte[9];
//按照规定字节读取,返回一个读取长度
int len = i.read(b);
System.out.println(new String(b)+"\t长度为:"+len);
i.close();
}
}
写操作:
![](https://i-blog.csdnimg.cn/blog_migrate/f5c31d6e7ef920c05d6e128e837934ea.png)
读操作:
![](https://i-blog.csdnimg.cn/blog_migrate/952145e87e8a15363c1d53b7b70062a9.png)