package files;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.LineNumberInputStream;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
public class TestIOStreamFilter {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
testDataStream();
testBufferedStream();
testLineNumberInputStream();
testPrintStream();
}
public static void testDataStream() throws IOException {
FileOutputStream fos = new FileOutputStream("./output.txt");
DataOutputStream dos = new DataOutputStream(fos);
dos.writeUTF("正则表达式");
dos.writeInt(1);
dos.writeDouble(1.11);
dos.writeChar('a');
dos.close();
fos.close();
FileInputStream fis = new FileInputStream("./output.txt");
DataInputStream dis = new DataInputStream(fis);
System.out.println(dis.readUTF());
System.out.println(dis.readInt());
System.out.println(dis.readDouble());
System.out.println(dis.readChar());
dis.close();
fis.close();
fis = new FileInputStream("./input.txt");
dis = new DataInputStream(fis);
byte[] bytes = new byte[100];
dis.read(bytes);
System.out.println(Charset.forName("UTF-8")
.decode(ByteBuffer.wrap(bytes)).toString());
dis.close();
fis.close();
}
public static void testBufferedStream() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos);
bos.write(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
bos.flush();
bos.write(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
bos.flush();
byte[] bytes = new byte[100];
BufferedInputStream bis = new BufferedInputStream(
new ByteArrayInputStream(baos.toByteArray()));
bis.read(bytes);
System.out.println(Arrays.toString(bytes));
bos.close();
baos.close();
bis.close();
}
public static void testLineNumberInputStream() throws IOException {
LineNumberInputStream lnis = new LineNumberInputStream(
new FileInputStream("./input.txt"));
byte[] bytes = new byte[100];
System.out.println(lnis.getLineNumber());
System.out.println(lnis.read(bytes, 0, 1));
System.out.println(lnis.getLineNumber());
lnis.setLineNumber(2);
System.out.println(lnis.read(bytes, 0, 1));
System.out.println(lnis.getLineNumber());
lnis.close();
}
public static void testPrintStream() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
ps.printf("%s%d", "number: ", 1);
System.out.println(Arrays.toString(baos.toByteArray()));
ps.close();
}
}
Java I/O 学习笔记(3) 基本输入输出流过滤
最新推荐文章于 2022-10-30 09:35:02 发布