操作文件流时不管字节流还是字符流都按照以下 的方式进行
1.使用File找到一个文件
2.通过File对象去实例化字节流和字符流的子类
3.进行字节(字符)的读写操作
4.关闭文件流
一、字节流 inputStream outputStream
package FileText;
/**
* 体会字节流的输入和输出
* int read(byte buffer[]);----------试图读取buffer.length个字节到buffer中,并返回实际成功读取的字节数
*/
import java.io.*;
public class ZiJieStreamText {
public static void main(String[] args) throws IOException {
File f=new File("c:\\abc\\aabcde.txt");
System.out.println(f.exists());
OutputStream out=null;
try {
out=new FileOutputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//写入字节
byte[] b="hello world!".getBytes();
out.write(b);
out.close();
//打印字节
InputStream in=null;
in=new FileInputStream(f);
byte b1[]=new byte [1024];
int i=0;
i=in.read(b1);
in.close();
System.out.println(new String(b1,0,i));
}
}
输出结果为
true
hello world!
字符流 Writer Reader
package FileText;
import java.io.*;
public class ZiFuStreamText {
public static void main(String[] args) throws IOException {
File f=new File("c:\\abc\\qwe.txt");//创建一个新的文件
//写入
Writer wr=new FileWriter(f);
String str="i love you";
wr.write(str);
wr.close();
//读出
Reader re=new FileReader(f);
char [] x=new char[1024];
int i=0;
i=re.read(x);
System.out.println(new String(x,0,i));
}
}
结果为
i love you