day21 java 语言中的读取写入数据(二)
一、概述:
使用IO流写文件,就体现的是下载的功能。所以说很有必要单独说一下。
二、写入功能:(下载)
写入功能同样也是被分隔为了字符流写入和字节流写入两个方式。
(一):字符流写入数据
1、FileWriter类。
2、bufferedwriter类。带缓冲流
(二):字节流写入数据
1、FileOutputStream类。
2、bufferoutputstream类。带有缓冲流
三、具体实例
(一):字符流写入数据
//io数据流输出【FileWriter】
package www.com.c2;
import java.io.FileWriter;
import java.io.IOException;
public class Io06 {
public static void main(String[] args) {
//1、准备要写入的数据
String str = "my name is ls";
try {
//2、创建实例,使用追加的方式写入
FileWriter fwa = new FileWriter("D:\\ls.txt",true);
//3、写入数据
fwa.write(str);
//4、关闭数据
fwa.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}//io数据流输出【bufferedwriter】
package www.com.c2;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Io08 {
public static void main(String[] args) {
try {
//1、创建实例
BufferedWriter bw =
new BufferedWriter(new FileWriter("D:\\ls.txt",true));
String str = "你好!我是李四。";
//2、写入
bw.write(str);
//3、清空缓冲区
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
} (二)字节流写入数据:
//io数据流输出【FileOutputStream】
package www.com.c2;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//输出流
/*
步骤:
1、准备你需要写的数据
2、创建fileoutputstream的对象
3、写入
*/
//注意:当你的文件在指定的路径下没有相应的文件时,就会创建相应的文件。
//如果有文件时默认就会替换里面的数据内容
public class Io05 {
public static void main(String[] args) {
//1、准备你需要写的数据
String str = "hello";
//将字符串转换为字符数组
byte[] bt = str.getBytes();
try {
//默认替换写入
//2、创建fileoutputstream的对象
FileOutputStream fos = new FileOutputStream("D:\\zs.txt");
//3、默认替换写入
fos.write(bt);
//4、关闭数据流
fos.close();
//追加的方式写入
//2.1在以后得数据基础上追加在以后得数据后面。类似于日志管理
FileOutputStream fo = new FileOutputStream("D://ls.txt", true);
//2.2追加写入
fo.write(bt);
//2.3关闭数据流
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}//io数据流输出【bufferoutputstream】
package www.com.c2;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Io07 {
public static void main(String[] args) {
try {
//1、创建实例追加在字段后面
BufferedOutputStream bops =
new BufferedOutputStream(new FileOutputStream("D:\\ls.txt",true));
//2、写入
bops.write("您好!".getBytes());
//3、清空缓冲区
bops.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}四、结束语:
到这里我们就讲读写文件数据学完了,就将常用的这几个学会就OK了
本文出自 “程序猿” 博客,转载请与作者联系!
原文地址:http://dzx123.blog.51cto.com/13270347/1980874