IO处理的其他类
------- android培训、java培训、期待与您交流! ----------
IO处理的其他类:
SequenceInputStream可将多个输入流合并成一个输入流。
其构造方法:
SequenceInputStream(InputStream s1, InputStream s2)
SequenceInputStream(Enumeration<? extends InputStream> e)
第一个构造方法比较简单,传入两个字节输入流就可以了。
第二个构造方法需要做一个集合,就流对象通过泛型放到集合中。代码:
import java.io.*;
import java.util.*;
class JoinFileInputStreamDemo {
public static void main(String[] args) throws IOException {
Vector<FileInputStream> v = new Vector<FileInputStream>();
v.add(new FileInputStream("d:/abc1.txt"));
v.add(new FileInputStream("d:/abc2.txt"));
v.add(new FileInputStream("d:/abc3.txt"));
Enumeration<FileInputStream> en = v.elements();
SequenceInputStream sis = new SequenceInputStream(en);
FileOutputStream fos = new FileOutputStream("d:/abc4.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.*;
import java.util.*;
class SplitFileDemo {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("d:/abc.avi");
int count = 1;
byte[] buf = new byte[1024 * 1024 * 50];
int len = 0;
while ((len = fis.read(buf)) != -1) {
FileOutputStream fos = new FileOutputStream("d:/abc.avi."
+ (count++) + ".part");
fos.write(buf, 0, len);
fos.close();
}
fis.close();
}
}
还有两个不是很常用类叫做,ObjectOutputStream和ObjectInputStream可将对象从内存中持久化到硬盘文件中,只是需要将需要持久化的对象所在的类实现Serializable接口,即implements Serializable。
另外,对于类中的static成员变量,将不会输出到持久化的文件中。如果不需要将非静态的成员变量持久化到文件中的话,可以将成员变量前加上transient修饰符。
这个类用的比较少,作为了解,就没有写代码。
管道流PipedInputStream和PipedOuteputStream。需要结合多线程技术,避免管道两端都在等待。虽然不常用,但是作为一个结合多线程的例子,可以学习一遍代码:
import java.io.*;
import java.util.*;
class PipedDemo {
public static void main(String[] args) throws IOException {
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream();
out.connect(in);
Read r = new Read(in);
Write w = new Write(out);
new Thread(r).start();
new Thread(w).start();
}
}
class Read implements Runnable {
private PipedInputStream in;
Read(PipedInputStream in) {
this.in = in;
}
public void run() {
try {
byte[] buf = new byte[1024];
System.out.println("管道in创建了");
int len = in.read(buf);
System.out.println("读到了数据,阻塞结束了");
String s = new String(buf, 0, len);
System.out.println(s);
}
catch (IOException e) {
throw new RuntimeException("管道输入流失败");
}
}
}
class Write implements Runnable {
private PipedOutputStream out;
Write(PipedOutputStream out) {
this.out = out;
}
public void run() {
try {
System.out.println("管道out创建了");
Thread.sleep(3000);
out.write("piped is coming".getBytes());
out.close();
}
catch (Exception e) {
throw new RuntimeException("管道输入流失败");
}
}
}
还有一个比较特殊的类RandomAccessFile,具备读写功能,它属于IO体系中,却直接继承Object类。这个类只能操作文件对象。
它的两个构造方法:
RandomAccessFile(File file, String mode)
RandomAccessFile(String name, String mode)
其mode只接受”r”、 ”rw”、 ”rws”、 ”rwd”四种。后两种不常用。

浙公网安备 33010602011771号