案例1:替换文本内容
需求说明:读取模板文件的内容,即把{name}、{type}、{master}替换为具体的宠物信息,将替换后的内容重新写入到文件中
public static void main(String[] args) throws IOException {
//读取文件里的文本
FileReader reader=new FileReader("E:\\txt.txt");
int i=0;
//定义变量接收文本
StringBuffer sb=new StringBuffer();
while ((i=reader.read())!=-1){
sb.append((char)i);
}
reader.close();
System.out.println("替换前:"+sb);
//定义String接收文本
String str=sb.toString();
//替换内容
str=str.replace("{name}","欧欧");
str=str.replace("{type}","狗");
str=str.replace("{master}","java");
System.out.println("替换后:"+str);
FileWriter writer=new FileWriter("E:\\txt.txt");
writer.write(str);
writer.close();
}
案例2:复制图片
FileInputStream in=new FileInputStream("E:\\jazlmo.jpg");
FileOutputStream out=new FileOutputStream("F:\\hsb.jpg");
DataInputStream input=new DataInputStream(in);
DataOutputStream output=new DataOutputStream(out);
int i=0;
while ((i=input.read())!=1){
output.write(i);
}
output.close();
input.close();
in.close();
out.close();
总的来说就是分为三部:1.创建流对象 2.调用方法 3.关闭相关的流对象