io输出流,四个步骤
1,建立联系
2,选择流
3,操作
4,释放资源
一起来看看代码吧
/**
* 操作文件过程
* 1,建立联系
* 2,选择流
* 3,操作,读写
* 4,释放资源
* @author snow
*
*/
public class IODemo {
public static void main(String[] args) {
// 1,建立联系
File file = new File("D:/lcm/zzq.txt");
// 2,选择流
FileOutputStream os = null;
try {
// 此处还有 一个构造方法 FileOutputStream(File file, boolean append)
// 当为true 时则为追加,默认为false
os = new FileOutputStream(file);
//将要输出的数据转成字节
String dataStr = "好好学习,天天向上\r\n加油!";
byte [] data = dataStr.getBytes("UTF-8");
//3,操作 => 输出
os.write(data, 0, data.length);
//强制刷新,将数据全部输出
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(os != null) {
try {
// 4, 关闭流
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}