黑马程序员-IO包中的常用类案例

来源:互联网 发布:c 二维数组赋值不全 编辑:程序博客网 时间:2024/04/27 22:25

------- android培训、java培训、期待与您交流! ----------


打印流  PrintWriter与printStream  可以直接操作输入流和文件。序列流:  SequenceInputStream  对多个流进行合并。操作对象  ObjectInputStream与ObjectOutputStream  被操作的对象需要实现Serializable(标记接口);

PrintStream类:

import java.io.FileNotFoundException;import java.io.IOException;import java.io.PrintStream;public class PrintDemo {public static void main(String[] args) throws IOException {/* * 1.提供了打印的方法可以对多种数据类型志进行打印并保持数据的表示形式 * 2.它不抛IO异常 * 构造函数,接收三种类型的值; * 1.字符串路径 * 2.File对象 * 3.字节输出流 */PrintStream out=new PrintStream("print.txt");//int by=read();out.write(610);//只写最低八位,//out.print(97);//将97线变成字符串,保持原样将数据打印到目的地out.close();}}

PrintWriter类:

package com.itheima.file;import java.io.BufferedReader;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;public class PrintWriterDemo {public static void main(String[] args) throws IOException {/* * 构造函数参数 * 1.字符串路径 * 2.File对象 * 3.字节输出流 *4.字符输出流 */BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));PrintWriter out=new PrintWriter(new FileWriter("out.txt"),true);String line=null;while((line=bufr.readLine())!=null){if("over".equals(line))break;out.println(line.toUpperCase());//out.flush();}out.close();bufr.close();}}

 需求:将1.txt、2.txt、3.txt文件中的数据合并到一个文件中

import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.SequenceInputStream;import java.util.ArrayList;import java.util.Collections;import java.util.Enumeration;public class SequenceInput {public static void main(String[] args) throws IOException {ArrayList<FileInputStream> al=new ArrayList<FileInputStream>();for(int x=1;x<=3;x++){al.add(new FileInputStream("1.txt"));al.add(new FileInputStream("2.txt"));al.add(new FileInputStream("3.txt"));}Enumeration<FileInputStream> en=Collections.enumeration(al);SequenceInputStream sis=new SequenceInputStream(en);FileOutputStream fos=new FileOutputStream("4.txt");byte[] buf=new byte[1024];int len=0;while((len=sis.read(buf))!=-1){fos.write(buf,0,len);}fos.close();sis.close();}}

文件切割器:

import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;/* * 文件切割器 *  */public class SplitFileDemo {private static final int SIZE = 1024 * 1024;public static void main(String[] args) throws IOException {File file=new File("d:\\幻听.mp3");splitFile(file);}public static void splitFile(File file) throws IOException {// 用读取流关联源文件FileInputStream fis = new FileInputStream(file);// 定义一个1M的缓冲区byte[] buf = new byte[SIZE];// 创建目的:FileOutputStream fos = null;int len = 0;int count = 1;File dir = new File("d:\\partFiles");if (!dir.exists()) {dir.mkdirs();}while ((len = fis.read(buf)) != -1) {fos = new FileOutputStream(new File(dir,(count++) + ".part"));fos.write(buf, 0, len);  fos.close();}fis.close();}}

文件的合并:

package com.itheima.file.io;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.SequenceInputStream;import java.util.ArrayList;import java.util.Collections;import java.util.Enumeration;public class MergeFile {public static void main(String[] args) throws IOException {File dir=new File("d:\\partFiles");mergeFile(dir);}public static void mergeFile(File dir) throws IOException {ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();for (int x = 1; x <= 7; x++) {al.add(new FileInputStream(new File(dir, x + ".part")));}Enumeration<FileInputStream> en=Collections.enumeration(al);SequenceInputStream sis = new SequenceInputStream(en);FileOutputStream fos=new FileOutputStream(new File(dir,"幻听.mp3"));byte[] buf=new byte[1024];int len=0;while((len=sis.read(buf))!=-1){fos.write(buf, 0, len);}fos.close();sis.close();}}

Properties集合:
package com.itheima.file;import java.util.Properties;import java.util.Set;public class PropertiesDemo {public static void main(String[] args) {/* * Map * |----Hashtable * |----Properties: * 特点: * 1.该集合中的键和值都是字符串类型 * 2.集合中的数据可以保存到流中,或者从流获取 *3.通常:该集合用于操作以键值对形式存在的配置文件。 */propertiesDemo();}/* * Properties集合的存和取 */public static void propertiesDemo(){//创建一个properties集合。Properties  prop=new Properties();//存储元素prop.setProperty("zhangsan", "30");prop.setProperty("lisi", "32");prop.setProperty("wangwu", "36");prop.setProperty("zhaoliu", "20");//修改元素prop.setProperty("zhangsan", "70");//取出所有元素Set<String> names=prop.stringPropertyNames();for(String name:names){String value=prop.getProperty(name);System.out.println(name+":"+value);}}}
package com.itheima.file.io.objectstream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import com.itheima.file.io.bean.Person;public class ObjectStreamDemo {public static void main(String[] args) throws IOException, ClassNotFoundException {//writeObj();readObj();}public static void readObj() throws IOException, ClassNotFoundException {ObjectInputStream ois=new ObjectInputStream(new FileInputStream("obj.object"));//对象的反序列化Person p=(Person)ois.readObject();System.out.println(p.getName()+":"+p.getAge());}public static void writeObj() throws IOException {ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("obj.object"));//对象序列化,被序列化的对象必须实现Serializable接口oos.writeObject(new Person("小强",30));oos.close();}}

序列化接口:

package com.itheima.file.io.bean;import java.io.Serializable;public class Person implements Serializable/*标记接口*/{/** *  */private static final long serialVersionUID = 1347L;/** *Serializable: 用于给序列化的类加入ID号。 *用与判断乐呵对象是否是同一个版本。 */private String name;private int age;public Person(String name, int age) {super();this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}

RandomAccessFile类:

随机访问访问文件,自身具备读写的方法。

通过skipBytesint x,seek(int x)来达到随机访问

package com.itheima.file.io.ramdomfile;import java.io.IOException;import java.io.RandomAccessFile;public class RandomAccessFileDemo {public static void main(String[] args) throws IOException {/* * RandomAccessFile * 一看这类的名字啊,纠结,不是IO体系中的子类。 *  * 特点: * 1.该对象又能写 * 2.该对象内部维护了一个byte数组,并通过指针可以操作数组中的元素。 * 3.可以通过getFilePointer方法获取指针的位置和通过seek方法设置指针的位置 * 4.其实该对象就是对字节输入流和字节输出流进行了封装。 * 5.该对象的源或者目的只能是文件。通过构造函数就可以看出。 *///writeFile();//readFile();randomWrite();}public static void randomWrite() throws IOException{RandomAccessFile raf=new RandomAccessFile("ranacc.txt","rw");//往指定位置写入数据。raf.seek(3*8);raf.write("哈哈".getBytes());raf.writeInt(102);raf.close();}public static void readFile() throws IOException {RandomAccessFile raf=new RandomAccessFile("ranacc.txt","r");//同过seek设置指针的位置raf.seek(1*8);//随机的读取,只要指定指正的位置即可。byte[] buf=new byte[4];raf.read(buf);String name=new String(buf);int age=raf.readInt();System.out.println("name="+name);System.out.println("age="+age);System.out.println("pos:"+raf.getFilePointer());raf.close();}//使用RandomAccessFile对象写入一些人员信息,比如姓名和年龄。public static void writeFile() throws IOException{/* * 如果文件不存在,则创建,如果文件存在,不创建 */ RandomAccessFile raf=new RandomAccessFile("ranacc.txt","rw");  raf.write("张三".getBytes()); raf.writeInt(88); raf.write("小强".getBytes()); raf.writeInt(66); raf.close();}}

管道流

PipedInputStreamPipedOutputStream

输入输出可以直接进行链接,通过结合线程使用。

package com.itheima.file.io.piped;import java.io.IOException;import java.io.PipedInputStream;import java.io.PipedOutputStream;public class PipedStream {public static void main(String[] args) throws IOException {PipedInputStream input=new PipedInputStream();PipedOutputStream output =new PipedOutputStream();input.connect(output);new Thread(new Input(input)).start();new Thread(new Output(output)).start();}}class Input implements Runnable{private PipedInputStream in;//构造函数public Input(PipedInputStream in) {super();this.in = in;}@Overridepublic void run() {try {byte[] buf=new byte[2];int len=0;while((len=in.read(buf))!=-1){String s=new String(buf,0,len);System.out.println("s="+s);}} catch (Exception e) {// TODO: handle exception}}}class Output implements Runnable{private PipedOutputStream out;public Output(PipedOutputStream out) {super();this.out = out;}@Overridepublic void run() {// TODO Auto-generated method stub try {out.write("hi,管道来了".getBytes());} catch (Exception e) {// TODO: handle exception}}}

操作基本数据类型:

DataInputStream与DataOutputStream

package com.itheima.file.io.datastream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class DataStreamDemo {public static void main(String[] args) throws IOException {//writeData();readData();}public static void readData() throws IOException {DataInputStream dis=new DataInputStream(new FileInputStream("data.txt"));System.out.println(dis.readUTF());dis.close();}public static void writeData() throws IOException {DataOutputStream dos=new DataOutputStream(new FileOutputStream("data.txt"));dos.writeUTF("你好");dos.close();}}

操作字节数组

ByteArrayInputStream与ByteArrayOutputStream

package com.itheima.file.io.bytestream;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;public class ByteArrayStreamDemo {public static void main(String[] args) {ByteArrayInputStream bis=new ByteArrayInputStream("hehe".getBytes());ByteArrayOutputStream bos=new ByteArrayOutputStream();int ch=0;while((ch=bis.read())!=-1){bos.write(ch);}System.out.println(bos.toString());}}

------- android培训、java培训、期待与您交流! ----------

0 0