1.字符流;分为两种,读和写;
***读;使用字符流类BufferReader和fileReader读写文本,BufferReader和fileReader都是Reader的子类,它们可以通过字符流来读取文件,并使用缓冲区提供读取文本的效率;
读取文本步骤如下;1>引入相关的类 2>构做一个BufferReader的对象 3>利用BufferReader的对象调用类的方法读取文本 4>关闭流对象
***写;使用字符流类BufferWriter和fileWriter写入文本,BufferWriter和fileWriter都是Writer的子类,它们可以通过字符流来写入文本,并使用缓冲区写入文本的效率
写入文本步骤如下;1>引入相关的类 2>构做一个BufferWriter的对象 3>利用BufferWriter的对象调用类的方法读取文本 4>关闭流对象
代码如下:public static void main(String[] args) {
BufferedReader bd=null;
Reader reader=null;
BufferedWriter bd1=null;
Writer w=null;
try {
w=new FileWriter("D:\\myprogame.txt");
bd1=new BufferedWriter(w);
reader=new FileReader("D:\\myprogame.txt");
bd=new BufferedReader(reader);
StringBuffer sb=new StringBuffer();
String line;
while((line=bd.readLine())!=null){
sb.append(line);
}
String str=sb.toString().replace("{name}", "狗狗").replace("{type}", "泰迪").replace("{master}", "张浩");
bd1.newLine();
bd1.write(str);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
if(bd!=null){
bd.close();
}
if(reader!=null){
reader.close();
}
if(bd1!=null){
bd1.close();
}
if(w!=null){
w.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.读写二进制文件:常用类有DataInputstream和DataOutputstream两种
***读方法:1>引入相关的类 2>构做一个数据输入源的对象 3>利用数据输入流类的方法读取文本 4>关闭流对象
***写方法:1>引入相关的类 2>构做一个数据输出源的对象 3>利用数据输出流类的方法读取文本 4>关闭流对象
代码如下:public static void main(String[] args) {
InputStream is=null;
DataInputStream di=null;
OutputStream op=null;
DataOutputStream os=null;
try {
is=new FileInputStream("D:\\tupian.jpg");
di=new DataInputStream(is);
op=new FileOutputStream("E:\\tupian1.jpg",true);
os=new DataOutputStream(op);
//输出流返回整型
int leng=0;
while((leng=di.read())!=-1){
os.write(leng);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(os!=null){
os.close();
}
if(op!=null){
op.close();
}
if(di!=null){
di.close();
}
if(is!=null){
is.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}