Java整理(六)IO

来源:互联网 发布:ubuntu双系统默认设置 编辑:程序博客网 时间:2024/05/23 01:12

编码问题

String s ="东南大学";
//字符串转换成字节数组
byte[] bytes = s.getBytes();//使用项目默认编码utf-8
byte[] bytes1 = s.getBytes("gbk");//指定编码
for (byteb:bytes){//把字节以16进制方式显示
   
System.out.println(Integer.toHexString(b&0xff));
}
//字节数组转换为字符串
String s_utf8=newString(bytes);
String s_gbk =new String(bytes1,"gbk");
//对应编码解码不正确会乱码
System.out.println(s_utf8);
System.out.println(s_gbk);

gbk编码中文占2字节,英文1字节

utf-8中文占3字节,英文1字节

字节序列变成字符串,需要用对应的编码方式,否则会乱码。

File类

File类只用表示文件或目录的信息(名称、路径、大小等),不能用于内容的访问。

import java.io.File;

File file = new File("./test");if (!file.exists()){//判断文件是否存在    file.createNewFile();//创建文件}file.isDirectory();//判断是否是目录file.isFile();//判断是否是文件file.mkdir();//只建一级目录file.mkdirs();//递归建立多级目录file.delete();//删除文件或目录for(String s:file.list()){//列出目录下文件    System.out.println(s);}for(File f :file.listFiles()){    System.out.println(f.getName());}

 

IO流

继承Inputstream或Reader的类都有read()方法,用于读取单个字节或者字节数组

继承Outputstream或Writer的类都有writer()方法,用于写单个字节或者字节数组

以上基本方法通常不会用到。


字节流

Inputstream抽象了应用程序读取数据的方式

Outputstream抽象了应用程序写出数据的方式

数据源包括:字节数组,String对象,文件,“管道”其他种类的流组成的序列,Internet连接等。

InputStream

功能

构造器参数

ByteArrayInputStream

将内存的缓冲区当做InputStream使用

缓冲区

StringBufferInputStream

String转换InputStream

字符串(StringBuffer)

FileInputStream

从文件读取信息

字符串,表文件名

PipedInputStream

用于写入PipedOutputStream

PipedOutputStream

SequenceInputStream

多个InputStream对象转换成单一InputStream

两个InputStream对象或容纳InputStream对象的容器Enumeration

FilterInputStream

抽象类,作为装饰器的接口

BufferedInputStream

DataInputStream

PushbakInputStream

DataInputStream

与DataOutputStream搭配,从流读取基本数据类型(int,char,long)

InputStream

BufferedInputStream

减少写操作

InputStream,可以指定缓冲区大小

PushbackInputStream

能弹出一个字节的缓冲区,可以将读到的最后一个字符回退

InputStream

 

OutputStream

功能

构造器参数

ByteArrayOutputStream

在内存中创建缓冲区

缓冲区初始化尺寸

FileOutputStream

用于将信息写至文件

字符串,表文件名

PipedOutputStream

用于PipedInputStream输出

PipedInputStream

FilterOutputStream

抽象类,作为装饰器

DataOutputStream

PrintStream

BufferedOutputStream

DataOutputStream

与DataInputStream搭配,从流读取基本数据类型(int,char,long)

OutputStream

PrintStream

用于产生格式化输出

DataOutputStream处理数据存储

PrintStream处理显示

OutputStream

BufferedOutputStream

减少写操作

OutputStream,可以指定缓冲区大小

举例

InputStream和OutputStream

try{    byte bWrite[] = {11, 21, 3, 40, 5};    OutputStream os = new FileOutputStream("test.txt");    for (int x = 0; x < bWrite.length; x++) {        os.write(bWrite[x]); // writes the bytes    }    os.close();    InputStream is = new FileInputStream("test.txt");    int size = is.available();    for (int i = 0; i < size; i++) {        System.out.print((char) is.read() + "  ");    }    is.close();} catch (IOException e) {    System.out.print("Exception");}

ByteArrayOutputStream和ByteArrayInputStream

byte[] bytes={1,2,3,127,-127};byte[] bytes1=new byte[10];ByteArrayInputStream bais=new ByteArrayInputStream(bytes);for (int i=0;i<5;i++){    System.out.println(bais.read());}bais.read(bytes1);//读取到字节数组中for(int i=0;i<10;i++)    System.out.println(bytes1[i]);ByteArrayOutputStream baos=new ByteArrayOutputStream(5);baos.write(3);baos.write(4);bytes1=baos.toByteArray();for (int i = 0; i < bytes1.length; i++)    System.out.println(bytes1[i]);

FileInputStream和FileOutputStream

这样效率低,仅仅作为学习

File file = new File("C:\\1.pdf");FileInputStream fin = new FileInputStream("C:\\1.pdf");FileOutputStream fout = new FileOutputStream("C:\\222.pdf");for(int i=0;i<file.length();i++) {    fout.write(fin.read());}

 

DataInputStream和DataOutputStream

DataInputStream dis = new DataInputStream(new FileInputStream("C:\\Users\\SUN\\Desktop\\a.txt"));DataOutputStream dos = new DataOutputStream(new FileOutputStream("C:\\Users\\SUN\\Desktop\\b.txt"));dos.writeChar(dis.readChar());//各种基本类型dos.writeInt(dis.readInt());dos.writeUTF("东南大学");//使用utf写入注意乱码问题dos.writeBytes("东南大学");dos.writeChars("东南大学");

 

字符流

InputStreamReader完成byte流解析为char流,按照编码解析

OutputStreamWriter完成char流到byte流

InputStreamReader isr = new InputStreamReader(        new FileInputStream("test.txt"),"utf-8");

 

BufferedReader 一次读一行readLine

BufferedWriter 一次写一行write();+ newline();//换行

File f = new File("test.txt");FileOutputStream fop = new FileOutputStream(f);// 构建FileOutputStream对象,文件不存在会自动新建OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8");// 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbkBufferedWriter bw = new BufferedWriter(writer);bw.append("中文输入");// 写入到缓冲区bw.append("\r\n");//换行bw.append("English");// 刷新缓存冲,写入到文件,如果下面已经没有写入的内容了,直接close也会写入bw.close();writer.close();fop.close();FileInputStream fip = new FileInputStream(f);// 构建FileInputStream对象InputStreamReader reader = new InputStreamReader(fip, "UTF-8");// 构建InputStreamReader对象,编码与写入相同StringBuffer sb = new StringBuffer();while (reader.ready()) {    sb.append((char) reader.read());    // 转成char加到StringBuffer对象中}System.out.println(sb.toString());reader.close();// 关闭读取流fip.close();// 关闭输入流,释放系统资源

 

对象的序列化、反序列化

对象序列化,将object转换为byte序列,反正为反序列化

序列化流ObjectOutputStream——writeObject()

反序列化流ObjectInputStream——readObject()

需要实现序列化接口(Serializable)

如:

ObjectOutputStream oos = new ObjectOutputStream(

new FileOutputStream(“file”));

Student stu = new Student(“10001”,”张三”,20);

oos.writeObject(stu);

oos.flush();

oos.close();

 

ObjectInputStream ois = newObjectInputStream(

                            newFileInputStream(file));

Student stu = (Student)ois.readObject();

ois.close();

注意transient修饰的元素不会进行jvm默认的序列化

如public transientint age;//在序列化时不会写入age值

 

 

 

原创粉丝点击