Java学习笔记之输入输出流(二) 缓冲流、随机流、数组流、数据流、对象流

来源:互联网 发布:windows日志在哪里 编辑:程序博客网 时间:2024/05/16 14:56

以下是博主学java的时候记的一些笔记,分享给大家,如果有错误或者以为的话,可以在下方留言


缓冲流(读一行)

BufferedReader类和BufferedWriter类创建的对象称为缓冲输入流、输出流,两者增强了读/写文件的能力。效率更高。

BufferedReader类的构造方法是:

BufferedReader(Reader in);

:FileReader fr = new FileReader(“hello.txt”);

   BufferedReader br = new BufferedReader(fr);

   String str = br.readLine();   

   readLine()读取文本行,当读到文件的末尾时,返回null;

   

BufferedWriter类的构造方法是:

BufferedWriter(Writer out);

:FileWriter fw = new FileWriter(“d:\\hello.txt”);

   BufferedWriter bw = new BufferedWriter(fw);

   bw.write(String s,int off,int len);

 

   BufferedWriter流有自己独特的向文件写入一个回行符的方法。

   bw.nextLine();

:

<span style="font-size:18px;">/** * 将一段字符串写入文本,然后copy到其他的目录下 */package com.File_1; import java.io.*;import java.nio.Buffer; public class huanchongliu { public static void main(String[] args) {// TODO Auto-generated method stubString str[] = {"大家好","我叫小明","很高兴认识大家","跟大家在一起很快乐","谢谢."};BufferedWriter bw = null;BufferedReader br = null;BufferedWriter bw2 = null;try {FileWriter file = new FileWriter("d:\\haha.txt");bw = new BufferedWriter(file);for(String s:str){bw.write(s);bw.newLine();}bw.close();file.close();FileReader fr = new FileReader("d:\\haha.txt");br = new BufferedReader(fr);String srr = null;FileWriter fw2 = new FileWriter("e:\\你好啊.txt");bw2 = new BufferedWriter(fw2);String sr = null;while((srr=br.readLine())!=null){System.out.println(srr);bw2.write(srr);}bw2.close();fr.close();br.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}</span>


//每个输入流输出流在用完的时候都要及时关闭,不然会发生一些未知的错误

 

随机流

RandomAccessFile类创建的对象称为随机访问文件流。

RandomAccessFile类创建的流和前面的输入流、输出流不同,RandomAccessFile类既是输入流,又是输出流。

 

RandomAccessFile类有两个构造方法:

RandomAccessFile(String name,String mode);参数name用来确定一个文件名,给出创建的流的源,也是流的目的地。参数moder(只读)rw(可读/),决定创建的流对文件的访问权利。

RandomAccessFile(File file,String mode);参数file是一个File对象,给出创建的流的源,也是流的目的地。参数moder(只读)rw(可读/),决定创建的流对文件的访问权利。

RandomAccessFile类中有一个方法seek(long a),用来定位RandomAccessFile流的读/写的位置,其中,参数a确定读/写位置距离文件开头的字节个数

流还可以调用getFilePointer()方法获取流的当前读/写位置。

 

 

 

:

<span style="font-size:18px;">/** * 随机流 ,了解RandomAccessFile类的使用 */package com.File_1; import java.io.*;import java.util.Arrays; public class shiyongwenbenduihuakuang { public static void main(String[] args) {// TODO Auto-generated method stubRandomAccessFile rda = null;RandomAccessFile rda2 = null;int data[] = {1,2,3,4,5,6,7,8,9,10,11};String s[] ={"nihao","dajiahao","jaj","hiuhf","oiuljl","ljhkfs"};try {rda = new RandomAccessFile("d:\\tent.txt", "rw");for(int i:data){rda.writeInt(i);/** * 这里存储在文本文档中的不是数字,而是乱码??????????? * 怎么解决???? *///System.out.println();}rda2 = new RandomAccessFile("d:\\rrr.txt","rw");for(String st:s){//System.out.println();rda2.writeBytes(st+"\r\n");//System.out.println();//rda2.seek(st.length());}rda2.close();for(int i=data.length-1;i>=0;i--){rda.seek(i*4);System.out.print(rda.readInt()+" ");}rda.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}</span>

答案:

<span style="font-size:18px;">11 10 9 8 7 6 5 4 3 2 1 </span>


RandomAccessFile流的readLine()方法在读取含有非ASCII字符的文件时(比如汉字)会出现乱码现象,因此,需要把readLine()读取的字符串用ISO-8859-1重新编码存放在byte数组中,然后用计算机默认编码成字符串。

:

<span style="font-size:18px;">/** * 将文档中的汉字用RandomAccessFile流中的readLine()输出出来 */package com.File_1; import java.io.*; public class suijiliu_2 { public static void main(String[] args) {// TODO Auto-generated method stubRandomAccessFile rda = null;try {rda = new RandomAccessFile("d:\\haha.txt", "rw");long length = rda.length();long con =0;rda.seek(con);while(con<length){String str = rda.readLine();byte b[] = str.getBytes("ISO-8859-1");     String str2 = new String(b);con = rda.getFilePointer();           //得到每一次读行之后的指针的位置System.out.println(str2);}rda.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}</span>


答案:

<span style="font-size:18px;">大家好我叫小明很高兴认识大家跟大家在一起很快乐谢谢. </span>


数组流

字节数组输出流ByteArrayInputStream和字节数组输出流ByteArrayOutputStream分别使用字节数组作为流的源和目标。

ByteArrayInputStream的构造方法是:

ByteArrayInputStream(byte[] buf);

ByteArrayInputStream(byte[] buf,int off,int len);

字节数组输出流调用public int read();方法可以顺序的读出一个字节,该方法返回读出的字节值,如果未读出字节,read()方法返回-1

ByteArrayOutputStream();

ByteArrayOutputStream(int size);

第一个构造方法构造的字节数组输出流指向一个默认大小为32个字节的缓冲区,第二个指向size大小的缓冲区,如果超过了缓冲区的容量,缓冲区的容量就会自动增加。

public void write(int b); 方法顺序的向缓冲区写入一个字节。

public void write(byte b[],int off,int len);

public byte[] toByteArray();  方法返回输出流写入缓存区的所示字节。

 

字节数组流对应的是字符数组流CharArrayReaderCharArrayWriter类,字符数组流分别使用字符数组作为流的源和目标。

 

:

<span style="font-size:18px;">/** * 使用数组流向内存(输出流的缓冲区)写入"How are you"和"您好",然后再从内存读取层写入的数据。 * 了解ByteArrayInputStream和ByteArrayOutputStream的用法(byte b[]) * 了解CharArrayReader和CharArrayWriter的用法(char c[]) */package com.File_2; import java.io.*; public class shuzuliu { public static void main(String[] args) throws Exception {// TODO Auto-generated method stubbyte b[] = "How are you".getBytes();   //用getBytes()方法将字符串转化成byte数组//System.out.println(b);ByteArrayOutputStream bao = new ByteArrayOutputStream();bao.write(b);ByteArrayInputStream bat = new ByteArrayInputStream(bao.toByteArray());   //返回输出流写入缓冲区的所示字节byte ba[] = new byte[bao.toByteArray().length];       bat.read(ba);                //将输入流的数据读入到ba[]中String s = new String(ba);     //将byte数组转化为String并输出System.out.println(s);                          char str[] = "您好".toCharArray();                    //同理用toCharArray()方法将汉字转化成char数组CharArrayWriter caw = new CharArrayWriter();caw.write(str);CharArrayReader car = new CharArrayReader(caw.toCharArray());char sr[] = new char[caw.toCharArray().length];car.read(sr);System.out.println(new String(sr));}}</span>


答案:

<span style="font-size:18px;">How are you您好</span>


 

数据流

DataInputStream类和DataOutputStream类创建的对象称为数据输入流和数据输出流。

DataInputStream类的构造方法是:

DataInputStream(InputStream in);  创建的数据输入流指向一个由参数in指定的底层输入流

 

DataOutputStream

DataOutputStream(OutputStream out);创建的数据输出流指向一个由参数out指定的底层输出流。

 

 

:

<span style="font-size:18px;">/** * 将几个java类型的数据写进一个文件中,然后再读出来 */package com.File_2; import java.io.*; public class shujuliu { public static void main(String[] args) {// TODO Auto-generated method stubFile file = new File("d:\\lalalal.txt");try{FileOutputStream fos = new FileOutputStream(file);DataOutputStream dos = new DataOutputStream(fos);dos.writeInt(120);                                  dos.writeFloat(3.1240f);//dos.writeInt(5200);dos.writeDouble(3.12045214);dos.writeChar('A');dos.writeChars("我叫小明");}catch(IOException e){}try{FileInputStream fis = new FileInputStream(file);DataInputStream dis = new DataInputStream(fis);System.out.println(dis.readInt());                              //这里read()的顺序要和上面write()的类型的顺序相同System.out.println(dis.readFloat());System.out.println(dis.readDouble());System.out.println(dis.readChar());//System.out.println(dis.readChar());//字符串类型的要单独对待,用while来控制char s ;             while((s=dis.readChar())!='\0'){System.out.print(s);                                     //'\0'表示空字符}}catch(IOException e){}} }/** * DataInputStream和DataOutputStream类要在两个异常中建立,否则字符串类型的read()时会出错**/</span>


答案:

<span style="font-size:18px;">1203.1243.12045214A我叫小明</span>


对象流

ObjectInoutStream类和ObjectOutputStream类创建的对象称为对象输入流和对象输出流。

对象输出流使用writeObject(Object obj)方法将一个对象obj写入到一个文件,对象输出流使用readObject()方法读取一个对象到程序中。

 

ObjectInoutStream类的构造函数是:

ObjectInoutStream(InputStream in);

:FileInputStream fis = new FileInputStream(d:tom.txt);

   ObjectInoutStream ois = new ObjectInoutStream(fis);

 

ObjectOutputStream类的构造方法如下:

ObjectOutputStream(OutputStrem out);

:FileOutputStream fos = new FileOutputStream(haha.txt);

   ObjectOutputStream oos = new ObjectOutputStream(fos);

 

 

知识点:

    把Java对象转换为字节序列的过程称为对象的序列化。     

    把字节序列恢复为Java对象的过程称为对象的反序列化。

      对象的序列化主要有两种用途:

    1) 把对象的字节序列永久地保存到硬盘上,通常存放在一个文件中;

2) 在网络上传送对象的字节序列。

 

 

 java.io.ObjectOutputStream代表对象输出流,

 它的writeObject(Object obj)方法可对参数指定的obj对象进行序列化,

 把得到的字节序列写到一个目标输出流中。

 java.io.ObjectInputStream代表对象输入流,

 它的readObject()方法从一个源输入流中读取字节序列,

 再把它们反序列化为一个对象,并将其返回。

 

 

 只有实现了SerializableExternalizable接口的类的对象才能被序列化。

 Externalizable接口继承自Serializable接口,

 实现Externalizable接口的类完全由自身来控制序列化的行为,

 而仅实现Serializable接口的类可以采用默认的序列化方式 。

 

 

 对象序列化包括如下步骤:

 1) 创建一个对象输出流,它可以包装一个其他类型的目标输出流,如文件输出流;

 2) 通过对象输出流的writeObject()方法写对象。

 对象反序列化的步骤如下:

 1) 创建一个对象输入流,它可以包装一个其他类型的源输入流,如文件输入流;

 2) 通过对象输入流的readObject()方法读取对象。

 

 

<span style="font-size:18px;">/** * 使用对象流读/写Student类创建的对象 */package com.File_2; import java.io.*; public class duixiangliu { public static void main(String[] args) {// TODO Auto-generated method stubStudents student = new Students();student.getNumber("小刚", 22, 176);try {FileOutputStream fos = new FileOutputStream("e:\\dasha.txt");ObjectOutputStream oos = new ObjectOutputStream(fos);oos.writeObject(student);fos.close();oos.close();FileInputStream fis = new FileInputStream("e:\\dasha.txt");ObjectInputStream ois = new ObjectInputStream(fis);Students stu = (Students)ois.readObject();System.out.println(stu.setS());System.out.println(stu.setData());System.out.println(stu.setShengao());stu.getNumber("小明", 20, 180);System.out.println(stu.setS());System.out.println(stu.setData());System.out.println(stu.setShengao());fis.close();ois.close();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} }class Students implements Serializable{String s;private int data;private double shengao;public void getNumber(String s,int data,double shengao){this.s = s;this.data = data;this.shengao = shengao;}public int setData(){return data;}public double setShengao(){return shengao;}public String setS(){return s;}}</span>


答案:

<span style="font-size:18px;">小刚22176.0小明20180.0</span>


0 0
原创粉丝点击