Java的字节流
字节输入流
package com.cnblogs;
import java.io.*;
/*
本类用于测试字节流的读取
*/
public class TestIn {
public static void main(String[] args) {
// method();//普通读取
method2();//高效
}
private static void method() {
InputStream in = null;
try {
// InputStream in2 = new FileInputStream(new File("E:eady1.txt"));
in = new FileInputStream("E:eady1.txt");
/*
一次读取一个字节,如果没有数据了,返回-1
*/
// System.out.println(in.read());//97
// System.out.println(in.read());//98
// System.out.println(in.read());//99
// System.out.println(in.read());//-1
// System.out.println(in.read());//-1
int result = 0;
while ((result = in.read()) != -1){
System.out.println(result);
}
} catch (Exception e) {
e.printStackTrace();
/*
finally代码块是try-catch结构中一定会执行到的部分,
常用于关流操作,为防止因发生异常没有正确关流,不能写在try{}
当中,这点需要注意
*/
}finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void method2() {
BufferedInputStream in1 = null;
try {
in1 = new BufferedInputStream(new FileInputStream("E:eady1.txt"));
int result = 0;
while((result = in1.read()) != -1){
System.out.println(result);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
in1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
字节输出流
package com.cnblogs;
import java.io.*;
/*
本类用于测试字节输出流
*/
public class TestOut {
public static void main(String[] args) {
// method();
method2();
}
private static void method() {
OutputStream out = null;
try {
out = new FileOutputStream("E:eady1.txt",true);
out.write(98);
out.write(99);
out.write(100);
/*
还可以使用两个参数的构造方法,来控制输出的数据是覆盖还剩追加,
默认为false,覆盖
如果为追加,第二个参数为true
*/
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();//关流后没法写入了
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void method2() {
OutputStream out = null;
try {
out =new BufferedOutputStream(new FileOutputStream("E:eady1.txt",true)) ;
out.write(101);
out.write(102);
out.write(103);
out.write(104);
out.write(105);
/*
还可以使用两个参数的构造方法,来控制输出的数据是覆盖还剩追加,
默认为false,覆盖
如果为追加,第二个参数为true
*/
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();//关流后没法写入了
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 »
Java的字节流