java流重定向如何分类,Java阶段之:处理流和重定向

7bcba8e9bc5a

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")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值