package file;
import java.io.*;
import java.nio.charset.Charset;
/**
* Created by Administrator on 2018/1/27.
* 输入输出流 示例
*/
public class TestFile {
public static void main(String[] args) {
//1 复制图片
try {
DataInputStream dis = new DataInputStream(new FileInputStream("D:\\花1.jpg"));
DataOutputStream dos = new DataOutputStream(new FileOutputStream("D:\\花2.jpg"));
int temp;
while ((temp = dis.read()) != -1){
dos.write(temp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
//2 序列化
try {
OutputStream out = new FileOutputStream("D:/Student1.class");
ObjectOutputStream oos = new ObjectOutputStream(out);
Student student = new Student();//Student要实现Serializable
student.setName("测试");
student.setScore(100d);
oos.writeObject(student);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
//3 反序列化
try {
InputStream is = new FileInputStream("D:/Student1.class");
ObjectInputStream ois = new ObjectInputStream(is);
Object oo = ois.readObject();
Student stu = (Student)oo;
System.out.println(stu.getName());
System.out.println(stu.getScore());
is.close();
} catch (Exception e) {
e.printStackTrace();
}
//4 替换文件内容
try{
// BufferedReader br = new BufferedReader(new FileReader("d:/pet.template"));//执行 bw.write(newString)后,写入的文件有乱码,故采用InputStreamReader
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("d:/pet.template"),"UTF-8"));
String ss = null;
StringBuffer sb = new StringBuffer();
while ((ss = br.readLine()) != null){
sb.append(ss);
}
System.out.println(sb.toString());
// FileWriter fw = new FileWriter("d:/pet1.txt");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("d:/pet1.txt"),"UTF-8"));
String newString = sb.toString().replace("{name}", "测试11").replace("{type}", "狗狗").replace("{master}", "拉拉");
bw.write(newString);
System.out.println(newString);
// bw.flush();//flush是清空缓冲区,就是立即输出到目标文件,而不是等缓冲区满了再输出,write只是将数据输出到缓冲区,还没有输出到目标文件。
bw.close();//关闭字符流就不用flush,不关闭的话只能flush后才能写入;close()会调用flush()
br.close();//如果一直不关闭流,就会导致内存被大量占用,以致程序崩溃
System.out.println(Charset.defaultCharset());
}catch (Exception e){
e.printStackTrace();
}
}
}
输入输出流 示例
猜你喜欢
转载自blog.csdn.net/danqiu2017/article/details/79181151
今日推荐
周排行