您的位置:首页 > 职场人生

黑马程序员----Java中的其他IO流

2015-08-24 11:45 399 查看
------- android培训java培训、期待与您交流! ----------

1.SequenceInputStream分割文件与合并文件传输

SequenceInputStream用来串联合并其他的输入文件流,文件切割通过不同的OutputSream实现。

package com.cn.filedemo;
import java.io.*;
import java.util.*;
/**
* 通过切割与合并复制文件Demo
*/
public class SequenceDemo {
public static void main(String[] args) {
divide();
// seqFile();//合并

}
static void divide(){//文件切割
FileInputStream fis=null;
FileOutputStream fos=null;//利用不同的OutputStream来切割
try {
fis=new FileInputStream("1.jpg");
int len=0,count=1;
byte[] buf=new byte[1024*30];//切割的大小
while((len=fis.read(buf))!=-1){
fos=new FileOutputStream("part"+count+++".part");
fos.write(buf,0,len);
fos.close();
}
} catch (Exception e) {
// TODO: handle exception
}finally{
try {
if(fis!=null)fis.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
}
static void seqFile(){//合并
SequenceInputStream sis=null;//通过SequenceInputStream来合并流
FileOutputStream fos=null;
try {
Vector<FileInputStream> v=new Vector<FileInputStream>();
v.add(new FileInputStream("1.txt"));
v.add(new FileInputStream("2.txt"));
v.add(new FileInputStream("3.txt"));
Enumeration<FileInputStream> e=v.elements();
sis=new SequenceInputStream(e);//SequenceInputStream只能接受Enumeration参数
fos=new FileOutputStream("4.txt");//输出到的文件
int len=0;byte[] buf=new byte[1024];
while((len=sis.read(buf))!=-1){//从SequenceInputStream读取
fos.write(buf,0,len);
fos.flush();
}

} catch (Exception e) {
e.printStackTrace();
}finally{//关闭资源
try {
if(sis!=null)sis.close();
} catch (Exception e2) {
e2.printStackTrace();
}
try {
if(fos!=null)fos.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}

2.ObjectIOStream
ObjectIOStream用来存储读取某个对象,所操作的对象的类必须实现Serinizeble接口

package com.cn.filedemo;

import java.io.*;
/**
* 用ObjectIOStream存储对象到文件
*/
class Person implements Serializable {//被ObjectIOStream操作的对象都要实现Serializable接口作为标识符
public static final long serialVersionUID =24L;//可以自己定义serialVersionUID标识符
public Person(String string, int i) {
this.name = string;
this.age = i;
}

@Override
public String toString(){
return this.name+"@@@@@"+this.age;
}
String name;
int age;
}

public class ObjectIOStream {
public static void main(String[] args) {
out();//通过ObjectOutputStream输出
in();//通过ObjectInputStream输出

}
static void in(){
ObjectInputStream ois =null;
try {
ois = new ObjectInputStream(new FileInputStream("obj.txt"));
Person p=(Person) ois.readObject();//需要强制类型转换
System.out.println(p.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (ois != null) {
ois.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
static void out() {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("obj.txt"));//传入要写入对象的文件
oos.writeObject(new Person("asdf", 44));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (oos != null) {
oos.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}

}

3.RandomAccessFile
RandomAccessFile最大的特点可以随机访问一个特定的长度,通过.skipBytes(int x),与seek(int x)等方法来达到随机访问的目的。

该对象即能读,又能写。因为其内部维护了一个数组,通过调用数组内部的指针达到这种效果,并且内部将字节流进行了封装。目的和源只能是文件。

package com.cn.filedemo;
import java.io.*;
/**
* RandomAccessFile用法
*/
public class RdmAcc {
public static void main(String[] args) throws Exception {
write();//写
read();//读
}

private static void read() throws Exception {
RandomAccessFile raf=new RandomAccessFile("raf.txt", "r");//只能读
byte[] buf=new byte[4];
raf.seek(8*2);//----------------跳过指针
raf.read(buf);//读一个固定长度的数组
String s=new String(buf);
System.out.println(s);
int i=raf.readInt();
System.out.println(i);
}

private static void write() throws Exception {
// TODO 自动生成的方法存根
RandomAccessFile raf=new RandomAccessFile("raf.txt", "rw");//可读写
raf.write("张三".getBytes());
raf.writeInt(97);
raf.write("李四".getBytes());
raf.writeInt(197);
raf.write("王五".getBytes());
raf.writeInt(44597);
raf.close();
}
}

4.管道流PipedIOputStream
用于线程间的传输

package com.cn.filedemo;
import java.io.*;
class InRun implements Runnable{//读入线程
PipedInputStream pis;//内部封装一个管道流
InRun(PipedInputStream i){
this.pis=i;
}
public void run() {
try {
System.out.println("开始读取");
byte[] buf=new byte [1024];
int len;
len = pis.read(buf);
String s=new String(buf,0,len);
System.out.println(s);
pis.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
class OutRun implements Runnable{//输出线程
PipedOutputStream pos;//内部封装一个输出管道流
OutRun(PipedOutputStream i){
this.pos=i;
}
public void run() {
try {
System.out.println("写入前睡一下");
Thread.sleep(4000);
System.out.println("开始写入");
pos.write("piped".getBytes());
pos.flush();
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
public class PipedIOStream {
public static void main(String[] args) throws IOException {
PipedInputStream pi=new PipedInputStream();
PipedOutputStream po=new PipedOutputStream();
pi.connect(po);
InRun ir=new InRun(pi);//将管道流传入
OutRun or =new OutRun(po);
new Thread(or).start();
new Thread(ir).start();

}
}

5.DataIOStream
一般用于少量基本数据的传输

6.ByteArrayIOStram

用操作流的方式操作数组

public class ByteArrayStream {
public static void main(String[] args) {
ByteArrayInputStream bais=new ByteArrayInputStream("asdvsdf".getBytes());//输入就是一个数组
ByteArrayOutputStream baos=new ByteArrayOutputStream();
int len=0;
while((len=bais.read())!=-1){
baos.write(len);
}
System.out.println(baos.toString());
}
}

7.IO流与集合综合案例
从键盘上输入学生三门成绩,统计总分并写入到集合,输出到文件

学生类

package com.cn.filedemo;

class Student implements Comparable<Student>{
//字段
private String name;
private int math;
private int en;
private int ch;
private int total;
//get,set
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getEn() {
return en;
}
public void setEn(int en) {
this.en = en;
}
public int getCh() {
return ch;
}
public void setCh(int ch) {
this.ch = ch;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public Student(String name,int math,int ch,int en){
this.name=name;
this.math=math;
this.ch=ch;
this.en=en;
this.total=math+ch+en;
}
@Override
public int hashCode(){
return name.hashCode()+math+ch+en+33*total;
}
@Override
public String toString(){
return "姓名"+name+"总分"+total;
}
@Override
public boolean equals(Object obj){
4000

if(!(obj instanceof Student)) return false;
Student t=(Student)obj;
return name.equals(t.name)&&math==t.math&&en==t.en&&ch==t.ch;
}

public int compareTo(Student stu){
int num=new Integer(this.total).compareTo(stu.total);
if(num==0){
num=name.compareTo(stu.name);
}
return num;
}

}

程序
package com.cn.filedemo;
import java.io.*;
import java.util.*;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils.Collections;
/**
* IO流中最后一个视频的联系
* 要求创建学生类,控制台输入三个成绩,得到的总成绩排序存入TreeSet,并输出到一个文件中
*/

public class LastTest {
public static void main(String[] args) {
System.out.println("请输入");

Set<Student>st=read();//通过键盘读取并写入集合
write(st);//写入到文件
}
static Set<Student> read(){//没有外部比较器时的读取
return read(null);
}
static Set<Student> read(Comparator<Student> cmp){//键盘读取
BufferedReader br=null;
Set<Student>st=null;
if(st==null){
st=new TreeSet<Student>();//因为要排序,所以采用TreeSet集合
}
else st=new TreeSet<Student>(cmp);//反转一下

try {
br=new BufferedReader(new InputStreamReader(System.in));
String line=null;
while((line=br.readLine())!=null){
if("over".equals(line))break;
String [] str=line.split(",");
Student s=new Student(str[0],Integer.parseInt(str[1]),Integer.parseInt(str[2]),Integer.parseInt(str[3]));
st.add(s);
}
} catch (Exception e) {
// TODO: handle exception
}finally{//关闭资源
try {
if(br!=null){
br.close();
}
} catch (Exception e2) {
// TODO: handle exception
}
}
return st;

}
static void write(Set<Student>st){//输出到文件
try{
PrintWriter pw=new PrintWriter(new FileOutputStream("stu.txt"),true);
Iterator<Student> it=st.iterator();
while(it.hasNext()){
Student s=it.next();
pw.println(s.toString());
System.out.println(s.toString());
}
pw.close();
}catch(Exception e){
e.printStackTrace();
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JavaSE IO流 集合框架