JAVA中的各种流
一.缓冲流:增加读写效率。
BufferedInputStream BufferedReader
BufferedOutputStream BufferedWriter
过程:1.使用节点流从磁盘将数据读取到内存的缓冲区
2.将内存缓冲区的数据读到缓冲流对应的缓冲区
3.缓冲流从缓冲流的缓冲区将数据读取到对应的地方去
tip:写入后需用flush刷新
public static void buffer_io_ch(String src,String des){
//字符型缓冲流
try {
//创建输入流
FileInputStream fis = new FileInputStream(src);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
//创建输出流
FileOutputStream fos = new FileOutputStream(des);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
int ch = 0;
while ((ch = br.read()) != -1){
bw.write(ch);
}bw.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void buffer_io_by(String src,String des){
//字节型缓冲流
try {
FileInputStream fis = new FileInputStream(src);
BufferedInputStream bi = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream(des);
BufferedOutputStream bo = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = bi.read(buffer)) != -1){
bo.write(buffer);
}bo.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
二.输入输出重定向:可使内容输出到特定的文件中或从特定的文件中输入
//输出重定向
public static void redirect_out(String des){
try {
FileOutputStream fos = new FileOutputStream(des);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
System.out.println("nihao ");
} catch (Exception e) {
e.printStackTrace();
}
}
//输入重定向
public static void redirect_in(String src){
try {
FileInputStream fis = new FileInputStream(src);
Scanner scanner = new Scanner(fis);
while (scanner.hasNext()){
System.out.println(scanner.next());
}
} catch (Exception e) {
e.printStackTrace();
}
}
三:读写对象
1.保存的类需要实现Sreializable接口
2.写入后需用flush刷新
//保存对象
public static void saveobject(String des){
try {
FileOutputStream fos = new FileOutputStream(des);
ObjectOutputStream os = new ObjectOutputStream(fos);
Person p = new Person("cu","19");
os.writeObject(p);
} catch (Exception e) {
e.printStackTrace();
}
}
//读取对象
public static void readobject(String des){
try {
FileInputStream fis = new FileInputStream(des);
ObjectInputStream ois = new ObjectInputStream(fis);
Person p = (Person) ois.readObject();
System.out.println(p);
} catch (Exception e) {
e.printStackTrace();
}
}
四.RandomAccessFile:实现在文件的某个位置读或者写
public static void randomAccess(String src){
try {
RandomAccessFile raf = new RandomAccessFile(src,"rw");
raf.seek(2);
raf.writeChars("hnm");
byte[] buffer = new byte[20];
raf.read(buffer);
System.out.println(new String(buffer));
} catch (Exception e) {
e.printStackTrace();
}
}
tip:"r"为只读 “rw”为读写 "rws" “rwd”同步写入
x.writeChars("xxx")