Java BIO实例

本文实例以文件操作、字节流、字符流、序列化流模块进行归纳,输入输出流同理部分缺省。

文件操作

java.io.File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class FileDemo {
public static void main(String[] args) {
File file = new File("E:\\javaio");
//System.out.println(file.exists());
if(!file.exists()){
file.mkdir(); //file.mkdirs()
else
file.delete();

//是否是一个目录 如果是目录返回true,如果不是目录or目录不存在返回的是false
System.out.println(file.isDirectory());
//是否是一个文件
System.out.println(file.isFile());

//File file2 = new File("e:\\javaio\\日记1.txt");
File file2 = new File("e:\\javaio","日记1.txt");
if(!file2.exists()){
try {
file2.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
else
file2.delete();

//常用的File对象的API
System.out.println(file);//file.toString()的内容
System.out.println(file.getAbsolutePath());
System.out.println(file.getName());
System.out.println(file2.getName());
System.out.println(file.getParent());
System.out.println(file2.getParent());
System.out.println(file.getParentFile().getAbsolutePath());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class FileDemo2 {
public static void main(String[] args) {
File file = new File("e:\\example");

//skill_01
String[] filenames = file.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
// TODO Auto-generated method stub
System.out.println(dir+"\\"+name);
return name.endsWith("java");
}
});
for (String string : filenames) {
System.out.println(string);
}

//skill_02
File[] files = file.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
// TODO Auto-generated method stub
System.out.println(dir+"\\"+name);
return false;
}
});

//skill_03
File[] files = file.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
// TODO Auto-generated method stub
System.out.println(pathname);
return false;
}
});
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class FileDemo3 {
public static void main(String[] args) {
File dir=new File("src/lee");
FileAccept fileAccept=new FileAccept();
fileAccept.setExtendName("java");
String[] fileName=dir.list(fileAccept);
for(String name:fileName){
System.out.println(name);
}
}
}
class FileAccept implements FilenameFilter{
private String extendName;
public void setExtendName(String s){
extendName="."+s;
}
@Override
public boolean accept(File dir, String name) {
// TODO Auto-generated method stub
return name.endsWith(extendName);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class FileDemo4 {
public static void main(String[] args) throws IOException {
File f=new File("E:\\workspace\\eclipse jee\\HelloWorld_01");
System.out.println(f.getName());
tree(f,1);
}
public static void tree(File f,int leve){
String str="";
for(int j=0;j<leve;j++){
str+=" ";
}
File[] children=f.listFiles();//list()方法返回字符串数组,目录下所有文件名
for(int i=0;i<children.length;i++){
System.out.println(str+children[i].getName());
if(children[i].isDirectory()){
tree(children[i],leve+1);
}
}
}
}

字节流

java.io.FileOutputStream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class FileOutDemo {
public static void main(String[] args) throws IOException {
//如果该文件不存在,则直接创建,如果存在,删除后创建
FileOutputStream out = new FileOutputStream("demo/out.dat");
out.write('A');//写出了'A'的低八位
out.write('B');//写出了'B'的低八位
int a = 10;//write只能写八位,那么写一个int需要些4次每次8位
out.write(a >>> 24);
out.write(a >>> 16);
out.write(a >>> 8);
out.write(a);
byte[] gbk = "中国".getBytes("gbk");
out.write(gbk);
out.close();
IOUtil.printHex("demo/out.dat");
}
}
1
2
3
4
5
6
7
8
9
try {
FileOutputStream fos=new FileOutputStream("a.txt");
fos.write("你好啊!".getBytes());
fos.flush();//清空缓存,立即输出缓存中的内容
fos.close();//关闭的时候也会清空缓存
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

java.io.FileInputStream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class FileInputDemo {
public static void main(String[] args) throws IOException {
FileInputStream input = new FileInputStream("demo/out.dat");
System.out.println(input.read());
System.out.println(input.read());
int i = 0;
i = input.read() | (i << 8);
i = input.read() | (i << 8);
i = input.read() | (i << 8);
i = input.read() | (i << 8);
System.out.println(i);
byte[] gbk = new byte[1024];
input.read(gbk);
System.out.println(new String(gbk));
input.close();
}
}
1
2
3
4
5
6
7
8
//默认的相对路径:就是我们的项目路径
FileInputStream fis=new FileInputStream("src/com/gem/sun/io/io.txt");
//read可以读取一个字符
//当文件比较大的时候,这种方式就读取不了了
byte[] bytes=new byte[fis.available()];
fis.read(bytes);
System.out.println(new String(bytes));
fis.close();

java.io.DataOutputStream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class DosDemo {
public static void main(String[] args) throws IOException {
String file = "demo/dos.dat";
DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
dos.writeInt(10);
dos.writeInt(-10);
dos.writeLong(10l);
dos.writeDouble(10.5);
//采用utf-8编码写出
dos.writeUTF("中国");
//采用utf-16be编码写出
dos.writeChars("中国");
dos.close();
IOUtil.printHex(file);
}
}

java.io.DataInputStream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class DisDemo {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
String file = "demo/dos.dat";
IOUtil.printHex(file);
DataInputStream dis = new DataInputStream(new FileInputStream(file));
int i = dis.readInt();
System.out.println(i);

i = dis.readInt();
System.out.println(i);

long l = dis.readLong();
System.out.println(l);

double d = dis.readDouble();
System.out.println(d);

String s = dis.readUTF();
System.out.println(s);
dis.close();
}
}

java.io.ByteArrayOutputStream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
File file=new File("a.txt");
//1.创建输出流
FileOutputStream fos=new FileOutputStream(file);
//创建数组
byte[] b=null;
//1.1如果是字符串
b="abc".getBytes();
//1.2他可能是一连串的数据
ByteArrayOutputStream bos=new ByteArrayOutputStream();//字节数组输出流
bos.write(b);//write就是将数据积累到bos

//2.向外输出内容
fos.write(bos.toByteArray());
//3.关闭输出流
fos.close();
1
2
3
4
5
6
7
8
9
10
11
12
ByteArrayOutputStream bos=new ByteArrayOutputStream();
//分段读取
FileInputStream fis=new FileInputStream("a.txt");
byte[] b=new byte[8];
int lenth=0;
while((lenth=fis.read(b))!=-1){
bos.write(b, 0, lenth);
//System.out.println(new String(b,0,b.length));
}
b=bos.toByteArray();
System.out.println(new String(b,"utf-8"));
fis.close();

java.io.PrintStream

1
2
3
4
5
FileOutputStream fos=new FileOutputStream("e:/test.txt");
PrintStream ps=new PrintStream(fos);
System.setOut(ps);
System.out.println(6666);
System.out.println(777);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class PrintStreamDemo {
public static void main(String[] args) throws IOException {
String filename=args[0];
if(filename!=null){
list(filename,System.out);
}
}
public static void list(String f,PrintStream fs){
try {
BufferedReader br=new BufferedReader(new FileReader(f));
String s=null;
while((s=br.readLine())!=null){
fs.println(s);
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

字符流

java.io.FileWriter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class FrAndFwDemo {
public static void main(String[] args) throws IOException{
FileReader fr = new FileReader("e:\\javaio\\fileWrite.txt");
FileWriter fw = new FileWriter("e:\\javaio\\fileWrite2.txt");
//FileWriter fw = new FileWriter("e:\\javaio\\fileWrite2.txt",true);
char[] buffer = new char[2056];
int c ;
while((c = fr.read(buffer,0,buffer.length))!=-1){
fw.write(buffer,0,c);
fw.flush();
}
fr.close();
fw.close();
}
}

java.io.FileReader

1
2
3
4
5
6
7
8
9
10
11
try {
FileReader fr=new FileReader("a.txt");
char[] chr=new char[1];
int lenth=0;
while((lenth=fr.read(chr))!=-1){
System.out.print(new String(chr));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

java.io.BufferedWriter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class BrAndBwOrPwDemo {
public static void main(String[] args) throws IOException{
//对文件进行读写操作
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("e:\\javaio\\imooc.txt")));
/*BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("e:\\javaio\\imooc3.txt")));*/
PrintWriter pw = new PrintWriter("e:\\javaio\\imooc4.txt");
//PrintWriter pw1 = new PrintWriter(outputStream,boolean autoFlush);
String line ;
while((line = br.readLine())!=null){
System.out.println(line);//一次读一行,并不能识别换行
/*bw.write(line);
//单独写出换行操作
bw.newLine();//换行操作
bw.flush();*/
pw.println(line);
pw.flush();
}
br.close();
//bw.close();
pw.close();
}
}

java.io.OutputStreamWriter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class IsrAndOswDemo {
public static void main(String[] args)throws IOException {
FileInputStream in = new FileInputStream("e:\\javaio\\imoocutf8.txt");
InputStreamReader isr = new InputStreamReader(in,"utf-8");//默认项目的编码,操作的时候,要写文件本身的编码格式
FileOutputStream out = new FileOutputStream("e:\\javaio\\imoocutf81.txt");
OutputStreamWriter osw = new OutputStreamWriter(out,"utf-8");
/*int c ;
while((c = isr.read())!=-1){
System.out.print((char)c);
}*/
char[] buffer = new char[8*1024];
int c;
/*批量读取,放入buffer这个字符数组,从第0个位置开始放置,最多放buffer.length个
返回的是读到的字符的个数
*/
while(( c = isr.read(buffer,0,buffer.length))!=-1){
String s = new String(buffer,0,c);
System.out.print(s);
osw.write(buffer,0,c);
osw.flush();
}
isr.close();
osw.close();
}
}

java.io.PrintWriter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class PrintWriterDemo {
public static void main(String[] args) throws IOException {
String s=null;
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
FileWriter fw=new FileWriter("e:/logfile.log",true);
PrintWriter log=new PrintWriter(fw);
while((s=br.readLine())!=null){
if(s.equalsIgnoreCase("exit")){
break;
}
System.out.println(s.toUpperCase());
log.println("------------");
log.println(s.toUpperCase());
log.flush();
}
log.println("==="+new Date()+"===");
log.flush();
log.close();
}
}

序列化流

java.io.RandomAccessFile

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class RafDemo {
public static void main(String[] args) throws IOException{
File demo = new File("demo");
if(!demo.exists()){
demo.mkdir();

File file = new File(demo,"raf.dat");
if(!file.exists()){
file.createNewFile();

RandomAccessFile raf = new RandomAccessFile(file, "rw");
//指针的位置
System.out.println(raf.getFilePointer());

raf.write('A');//只写了一个字节
System.out.println(raf.getFilePointer());
raf.write('B');

int i = 0x7fffffff;
//用write方法每次只能写一个字节,如果要把i写进去就得写4次
raf.write(i >>> 24);//高8位
raf.write(i >>> 16);
raf.write(i >>> 8);
raf.write(i);
System.out.println(raf.getFilePointer());

//可以直接写一个int
raf.writeInt(i);

String s = "中";
byte[] gbk = s.getBytes("gbk");
raf.write(gbk);
System.out.println(raf.length());

//读文件,必须把指针移到头部
raf.seek(0);
//一次性读取,把文件中的内容都读到字节数组中
byte[] buf = new byte[(int)raf.length()];
raf.read(buf);

System.out.println(Arrays.toString(buf));
for (byte b : buf) {
System.out.println(Integer.toHexString(b & 0xff)+" ");
}
raf.close();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class RafReadDemo {
public static void main(String[] args)throws IOException {
RandomAccessFile raf = new RandomAccessFile("demo/raf.dat", "r");
raf.seek(2);
int i = 0;
int b = raf.read();//读取到一个字节
System.out.println(raf.getFilePointer());
i = i | (b << 24 );
b = raf.read();
i = i | ( b << 16);
b = raf.read();
i = i | (b << 8 );
b = raf.read();
i = i | b;
System.out.println(Integer.toHexString(i));
raf.seek(2);
i = raf.readInt();
System.out.println(Integer.toHexString(i));
raf.close();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class RandomAccessFileSeriaDemo {
public static void main(String[] args)throws IOException {
File demo = new File("demo1");
if(!demo.exists()){
demo.mkdir();

File file = new File(demo,"raf.dat");
if(!file.exists()){
file.createNewFile();

//打开文件,进行随机读写
RandomAccessFile raf = new RandomAccessFile(file, "rw");
/*序列化*/
int i = 0x7ffffff;
raf.write(i >>> 24);
raf.write(i >>> 16);
raf.write(i >>> 8);
raf.write(i >>> 8);
raf.write(i);
System.out.println(raf.getFilePointer());

/*反序列化*/
raf.seek(0);
int b = raf.read();
i = i | (b << 24);
b = raf.read();
i = i | (b << 16);
b = raf.read();
i = i | (b << 8);
b = raf.read();
i = i | b;
System.out.println(Integer.toHexString(i));
raf.close();
}
}

java.io.ObjectOutputStream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class Student implements Serializable{
private String stuno;
private String stuname;
//该元素不会进行jvm默认的序列化,也可以自己完成这个元素的序列化
private transient int stuage;

public Student(String stuno, String stuname, int stuage) {
super();
this.stuno = stuno;
this.stuname = stuname;
this.stuage = stuage;
}

public String getStuno() {
return stuno;
}
public void setStuno(String stuno) {
this.stuno = stuno;
}
public String getStuname() {
return stuname;
}
public void setStuname(String stuname) {
this.stuname = stuname;
}
public int getStuage() {
return stuage;
}
public void setStuage(int stuage) {
this.stuage = stuage;
}
@Override
public String toString() {
return "Student [stuno=" + stuno + ", stuname=" + stuname
+ ", stuage=" + stuage + "]";
}
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
s.defaultWriteObject();//把jvm能默认序列化的元素进行序列化操作
s.writeInt(stuage);//自己完成stuage的序列化
}
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException{
s.defaultReadObject();//把jvm能默认反序列化的元素进行反序列化操作
this.stuage = s.readInt();//自己完成stuage的反序列化操作
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class ObjectSeriaDemo1 {
public static void main(String[] args) throws Exception{
String file = "demo/obj.dat";
//1.对象的序列化
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(file));
Student stu = new Student("10001", "张三", 20);
oos.writeObject(stu);
oos.flush();
oos.close();

//2.对象的反序列化
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(file));
Student stu = (Student)ois.readObject();
System.out.println(stu);
ois.close();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
public class ObjectSeriaDemo2 {
public static void main(String[] args) throws Exception{
//序列化过程递归调用父类的构造函数
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("demo/obj1.dat"));
Foo2 foo2 = new Foo2();
oos.writeObject(foo2);
oos.flush();
oos.close();

//反序列化不递归调用父类的构造函数
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("demo/obj1.dat"));
Foo2 foo2 = (Foo2)ois.readObject();
System.out.println(foo2);
ois.close();

//序列化过程递归调用父类的构造函数
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("demo/obj1.dat"));
Bar2 bar2 = new Bar2();
oos.writeObject(bar2);
oos.flush();
oos.close();

/*
* 对子类对象进行反序列化操作时,
* 如果其父类没有实现序列化接口
* 那么其父类的构造函数会被调用
*/
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("demo/obj1.dat"));
Bar2 bar2 = (Bar2)ois.readObject();
System.out.println(bar2);
ois.close();
}
}
/*
* 一个类实现了序列化接口,那么其子类都可以进行序列化
*/
class Foo implements Serializable{
public Foo(){
System.out.println("foo...");
}
}
class Foo1 extends Foo{
public Foo1(){
System.out.println("foo1...");
}
}
class Foo2 extends Foo1{
public Foo2(){
System.out.println("foo2...");
}
}
class Bar{
public Bar(){
System.out.println("bar");
}
}
class Bar1 extends Bar{
public Bar1(){
System.out.println("bar1..");
}
}
class Bar2 extends Bar1 implements Serializable{
public Bar2(){
System.out.println("bar2...");
}
}
0%